package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import oracle.net.aso.a;
//
//import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

//import com.google.zxing.client.result.BizcardResultParser;

import cn.com.api.entity.ApiAddress;
import cn.com.api.entity.ApiCar;
import cn.com.api.entity.ApiDianPing;
import cn.com.api.entity.ApiDingAss;
import cn.com.api.entity.ApiDingDan;
import cn.com.api.entity.ApiJuan;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiT_goods_activity;
//import cn.com.api.entity.ApiT_juan_tj;
import cn.com.api.entity.ApiT_member_point;
import cn.com.api.entity.ApiT_products;
import cn.com.api.entity.ApiT_shipper_account;
import cn.com.api.entity.ApiT_shipping;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.Cond;
import cn.com.api.mapper.ApiAddressMapper;
import cn.com.api.mapper.ApiCarMapper;
import cn.com.api.mapper.ApiDianPingMapper;
import cn.com.api.mapper.ApiDingAssMapper;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiJuanMapper;
import cn.com.api.mapper.ApiJuanTJMapper;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiT_cityMapper;
import cn.com.api.mapper.ApiT_goods_activityMapper;
import cn.com.api.mapper.ApiT_member_pointMapper;
import cn.com.api.mapper.ApiT_orderMapper;
import cn.com.api.mapper.ApiT_productsMapper;
import cn.com.api.mapper.ApiT_shipper_accountMapper;
import cn.com.api.mapper.ApiT_shippingMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.requestpage.CancelReasonPage;
import cn.com.api.requestpage.OrderConfirmPage;
import cn.com.api.requestpage.SearchOrdersPage;
import cn.com.api.requestpage.SendOrderPage;
import cn.com.api.requestpage.ShopOrderPage;
import cn.com.api.resultpage.AccountPage;
import cn.com.api.resultpage.CarOrderPage;
import cn.com.api.resultpage.CarShopPage;
import cn.com.api.resultpage.InitAccountPage;
import cn.com.api.resultpage.InitMyOrderPage;
import cn.com.api.resultpage.InitMyOrderPage2;
import cn.com.api.resultpage.InitOrderInfoPage;
import cn.com.api.resultpage.InitOrderPage;
import cn.com.api.resultpage.InitPaymentPage;
import cn.com.api.resultpage.InitSendOrderPage;
import cn.com.api.resultpage.InitShopOrderPage;
import cn.com.api.resultpage.InitUserOrderStatusPage;
import cn.com.api.resultpage.MyOrderPage;
import cn.com.api.service.ApiCarService;
import cn.com.api.service.ApiCommonService;
import cn.com.api.service.ApiGoodsService;
import cn.com.api.service.ApiJuanService;
import cn.com.api.service.ApiOrderService;
import cn.com.api.service.ApiShopsService;
import cn.com.api.service.ApiTOrderMessageService;
import cn.com.api.service.ApiT_juan_tjService;
import cn.com.api.service.ApiT_log_userService;
import cn.com.api.service.ApiT_points_ruleService;
import cn.com.api.service.ApiT_productsService;
import cn.com.api.service.ApiT_recommend_couponService;
import cn.com.api.service.ApiT_shippingService;
import cn.com.api.service.StartOnLoadService;
import cn.com.util.*;
@Service
public class ApiOrderServiceImpl implements ApiOrderService {
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	@Autowired
	private ApiAddressMapper apiAddressMapper;
	@Autowired
	private ApiCarMapper apiCarMapper;
	@Autowired
	private ApiDingDanMapper apiDingDanMapper;
	@Autowired
	private ApiDingAssMapper apiDingAssMapper;
	@Autowired
	private ApiGoodsService apiGoodsService;
	@Autowired
	private ApiCommonService apiCommonService;
	@Autowired
	private ApiT_shippingService apiT_shippingService;
	@Autowired
	private ApiT_juan_tjService apiT_juan_tjService;
	@Autowired
	private ApiJuanService apiJuanService;
	@Autowired
	private StartOnLoadService startOnLoadService;
	@Autowired
	private ApiCarService apiCarService;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	@Autowired
	private ApiT_shippingMapper apiT_shippingMapper;
	@Autowired
	private ApiDianPingMapper apiDianPingMapper;
	@Autowired
	private ApiT_productsMapper apiT_productsMapper;
	@Autowired
	private ApiJuanMapper apiJuanMapper;
	@Autowired
	private ApiJuanTJMapper apiJuanTJMapper;
	@Autowired
	private ApiT_cityMapper cityMapper;
	@Autowired
	private ApiT_shipper_accountMapper apiT_shipper_accountMapper;
	@Autowired
	private ApiT_goods_activityMapper apiT_goods_activityMapper;
	@Autowired
	private ApiT_productsService apiT_productsService;
	@Autowired
	private ApiT_log_userService apiT_log_userService;
	@Autowired
	private ApiT_points_ruleService apiT_points_ruleService;
	@Autowired
	private ApiTOrderMessageService apiTOrderMessageService;
	@Autowired
	private ApiT_recommend_couponService apiT_recommend_couponService;
	@Autowired
	private ApiShopsService apiShopsService;
	@Autowired
	private ApiT_member_pointMapper apiT_member_pointMapper;
	@Autowired
	private ApiT_orderMapper apiT_orderMapper;

	private static Logger logger = Logger.getLogger(ApiOrderServiceImpl.class);

	/**
	 * 返回：shopList:List<CarShopPage> shopList sumPrice:double sumPrice
	 * 
	 * @param c_ids
	 * @return
	 */
	@Override
	public InitOrderPage getShopListByCids(String c_ids) {
		InitOrderPage initOrderPage = new InitOrderPage();
		String[] cidArrayStr = c_ids.split(",");
		List<Integer> cidList = new ArrayList<Integer>();
		BigDecimal sumPrice = BigDecimal.ZERO;
		BigDecimal sumSendfee = BigDecimal.ZERO;
		for (String cidStr : cidArrayStr) {
			Integer cid = Integer.parseInt(cidStr);
			cidList.add(cid);
		}
		List<CarOrderPage> carList = apiCarMapper.searchCarGoodsByCidsBeforeOrder(cidList);
		List<CarShopPage> shopList = new ArrayList<CarShopPage>();
		if (carList != null && carList.size() > 0) {
			Map<Integer, String> shopIds = new HashMap<Integer, String>();
			Integer city_id = carList.get(0).getCity_id();
			ApiT_city city = cityMapper.findT_cityById(city_id);
			BigDecimal sendfee = city.getSendfee();// 配送费
			BigDecimal defaultSendPrice = city.getSendlimit();// 配送额度
			for (CarOrderPage carpage : carList) {
				Integer shopId = carpage.getShop_id();
				String shopName = carpage.getShopName();
				if (shopIds.containsKey(shopId)) {
					for (CarShopPage shop : shopList) {
						if (("" + shop.getShop_id()).equals(shopId + "")) {
							shop.getCarList().add(carpage);
							BigDecimal allCardMoney=carpage.getPrice().multiply(Util.getBigDecimal(carpage.getCount().toString()));
							shop.setSumShopPrice(shop.getSumShopPrice().add(allCardMoney));
							sumPrice = sumPrice.add(allCardMoney);
							shop.setGoodscount(shop.getGoodscount() + carpage.getCount());
						}
					}
				} else {
					List<CarOrderPage> shopCarList = new ArrayList<CarOrderPage>();
					CarShopPage shopPage = new CarShopPage();
					shopCarList.add(carpage);
					BigDecimal allCardMoney=carpage.getPrice().multiply(Util.getBigDecimal(carpage.getCount().toString()));
					sumPrice = sumPrice.add(allCardMoney);
					shopPage.setShop_id(shopId);
					shopPage.setShop_name(shopName);
					shopPage.setIs_ziying(carpage.getIs_ziying());
					shopPage.setIs_lunchbox(carpage.getIs_lunchbox());
					shopPage.setLunchbox_price(carpage.getLunchbox_price());
					shopPage.setGoodscount(carpage.getCount());
					shopPage.setCarList(shopCarList);
					BigDecimal sumShopPrice = allCardMoney;
					shopPage.setSumShopPrice(sumShopPrice);
					shopList.add(shopPage);
					shopIds.put(shopId, "");
				}
			}
			for (CarShopPage page : shopList) {
				Integer is_lunchbox = page.getIs_lunchbox();
				BigDecimal lunchbox_price = page.getLunchbox_price();
				if (1 == is_lunchbox) {// 判断该店铺是否启用餐盒费
					Integer goodsCount = page.getGoodscount();
					BigDecimal sum_lunchbox_price =Util.getBigDecimal(goodsCount.toString()).multiply(lunchbox_price);
					page.setSum_lunchbox_price(sum_lunchbox_price);
					page.setSumShopPrice(page.getSumShopPrice().add(sum_lunchbox_price) );
				}
				// 加完餐盒费之后再计算配送费
				if (page.getSumShopPrice().compareTo(defaultSendPrice)==-1) {
					page.setSendfee(sendfee);
				}else {
					page.setSendfee(BigDecimal.ZERO);
				}
				/*if (page.getSumShopPrice() < defaultSendPrice) {
					page.setSendfee(sendfee);
				} else {
					page.setSendfee(0.0);
				}*/

				sumSendfee = sumSendfee.add(page.getSendfee());

				// 每个商铺可用的优惠券
				Map<String, Object> juan = new HashMap<String, Object>();
				CarOrderPage clist = new CarOrderPage();
				clist = page.getCarList().get(0);
				String goods = "";
				for (CarOrderPage c : page.getCarList()) {
					goods += c.getGoods_id() + ",";
				}
				// String money, String[] citys,String[] shops, String
				// uid,Map<String,Object> res,String products
				apiJuanService.payJuan(page.getSumShopPrice() + "", new String[] { clist.getCity_id() + "", "-1" },
						new String[] { page.getShop_id() + "", "-1" }, clist.getUid(), juan, goods);
				List<Map<String, String>> list = new ArrayList<Map<String, String>>();
				list = (List<Map<String, String>>) juan.get("datas");
				page.setJuanCount(list.size());
			}

		}
		initOrderPage.setSumPrice(sumPrice);
		initOrderPage.setShopList(shopList);
		initOrderPage.setSendfee(sumSendfee);
		return initOrderPage;
	}

	/**
	 * 返回：productList:List<ProductPage> productList sumPrice:double sumPrice
	 * 充值有礼---不计配送费
	 * 
	 * @param product_ids
	 * @return
	 */
	@Override
	public InitOrderPage getProductListByproductids(String product_ids) {
		InitOrderPage initOrderPage = new InitOrderPage();
		String[] productidArrayStr = product_ids.split(",");
		List<Long> productidList = new ArrayList<Long>();
		BigDecimal sumPrice =BigDecimal.ZERO;
		BigDecimal sumSendfee =BigDecimal.ZERO;
		for (String cidStr : productidArrayStr) {
			Long cid = Long.valueOf(cidStr);
			productidList.add(cid);
		}
		List<CarOrderPage> carList = apiT_productsMapper.searchProductsByProductIds(productidList);
		List<CarShopPage> shopList = new ArrayList<CarShopPage>();
		if (carList != null && carList.size() > 0) {
			Map<Integer, String> shopIds = new HashMap<Integer, String>();
			for (CarOrderPage carpage : carList) {
				Integer shopId = carpage.getShop_id();
				String shopName = carpage.getShopName();
				carpage.setCount(1);
				if (shopIds.containsKey(shopId)) {
					for (CarShopPage shop : shopList) {
						if (("" + shop.getShop_id()).equals(shopId + "")) {
							shop.getCarList().add(carpage);
							BigDecimal allCarMoney=carpage.getPrice().add(Util.getBigDecimal(carpage.getCount().toString()));
							shop.setSumShopPrice(shop.getSumShopPrice().add(allCarMoney));
							sumPrice = sumPrice.add(allCarMoney);
						}
					}
				} else {
					List<CarOrderPage> shopCarList = new ArrayList<CarOrderPage>();
					CarShopPage shopPage = new CarShopPage();
					shopCarList.add(carpage);
					BigDecimal allCarMoney=carpage.getPrice().add(Util.getBigDecimal(carpage.getCount().toString()));
					sumPrice = sumPrice.add (allCarMoney);
					shopPage.setShop_id(shopId);
					shopPage.setShop_name(shopName);
					shopPage.setIs_ziying(carpage.getIs_ziying());
					shopPage.setCarList(shopCarList);
					BigDecimal sumShopPrice = allCarMoney;
					shopPage.setSumShopPrice(sumShopPrice);
					shopPage.setSendfee(BigDecimal.ZERO);
					shopList.add(shopPage);
					shopIds.put(shopId, "");
				}
			}
		}
		initOrderPage.setSumPrice(sumPrice);
		initOrderPage.setShopList(shopList);
		initOrderPage.setSendfee(sumSendfee);
		return initOrderPage;
	}

	@Override
	public InitOrderPage getProductListByactids(String act_ids) {
		InitOrderPage initOrderPage = new InitOrderPage();
		String[] act_idsArrayStr = act_ids.split(",");
		List<Integer> act_idsList = new ArrayList<Integer>();
		BigDecimal sumPrice =BigDecimal.ZERO;
		// 积分兑换 不考虑配送费
		BigDecimal sumSendfee =BigDecimal.ZERO;
		Integer sumPoints = 0;
		for (String cidStr : act_idsArrayStr) {
			Integer cid = Integer.parseInt(cidStr);
			act_idsList.add(cid);
		}
		List<CarOrderPage> carList = apiT_goods_activityMapper.searchProductsByActIds(act_idsList);
		List<CarShopPage> shopList = new ArrayList<CarShopPage>();
		if (carList != null && carList.size() > 0) {
			Map<Integer, String> shopIds = new HashMap<Integer, String>();
			for (CarOrderPage carpage : carList) {
				Integer shopId = carpage.getShop_id();
				String shopName = carpage.getShopName();
				carpage.setCount(1);
				if (shopIds.containsKey(shopId)) {
					for (CarShopPage shop : shopList) {
						if (("" + shop.getShop_id()).equals(shopId + "")) {
							shop.getCarList().add(carpage);
							BigDecimal count=Util.getBigDecimal(carpage.getCount().toString());
							BigDecimal carPrice=carpage.getPrice().multiply(count);
							BigDecimal allMoney=shop.getSumShopPrice().add(carPrice);
							shop.setSumShopPrice(allMoney);
							sumPrice = sumPrice.add(carPrice);
							shop.setSendfee(BigDecimal.ZERO);
							sumPoints = sumPoints + carpage.getPoints();
							shop.setSumPoints(shop.getSumPoints() + carpage.getPoints());
						}
					}
				} else {
					List<CarOrderPage> shopCarList = new ArrayList<CarOrderPage>();
					CarShopPage shopPage = new CarShopPage();
					shopCarList.add(carpage);
					BigDecimal count=Util.getBigDecimal(carpage.getCount().toString());
					BigDecimal carPrice=carpage.getPrice().multiply(count);
					sumPrice = sumPrice.add(carPrice);
					shopPage.setShop_id(shopId);
					shopPage.setShop_name(shopName);
					shopPage.setIs_ziying(carpage.getIs_ziying());
					shopPage.setCarList(shopCarList);
					BigDecimal sumShopPrice = carPrice;
					shopPage.setSumShopPrice(sumShopPrice);
					shopPage.setSendfee(BigDecimal.ZERO);
					shopPage.setSumPoints(carpage.getPoints());
					sumPoints = sumPoints + carpage.getPoints();
					shopList.add(shopPage);
					shopIds.put(shopId, "");
				}
			}
			for (CarShopPage page : shopList) {
				sumSendfee = sumSendfee.add(page.getSendfee());
			}
		}
		initOrderPage.setSumPrice(sumPrice);
		initOrderPage.setShopList(shopList);
		initOrderPage.setSendfee(sumSendfee);
		initOrderPage.setSumPoints(sumPoints);
		return initOrderPage;
	}

	@Override
	public void initOrder(String u_id, String c_ids, Map<String, Object> map) {
		InitOrderPage orderPage = new InitOrderPage();
		// 根据u_id 返回用户信息，默认收货地址
		ApiTmember member = new ApiTmember();
		member = apiTmemberMapper.findMemberByCuserid(u_id);
		// t_address 收货地址
		ApiAddress address = apiAddressMapper.searchAddressByUid(u_id);
		// 如果没有默认地址---则返回地址中的第一个
		if (address == null) {
			List<ApiAddress> addressList = apiAddressMapper.searchAllAddressByUid(u_id);
			if (addressList != null && addressList.size() > 0) {
				address = addressList.get(0);
			}
		}
		// 解析购物单c_ids---不用解析，直接去数据库查询 in
		orderPage = getShopListByCids(c_ids);
		orderPage.setMember(member);
		orderPage.setAddress(address);
		map.put("datas", orderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	@Transactional
	@Override
	public void confirmOrder(OrderConfirmPage orderConfirmPage, Map<String, Object> map) throws Exception {
		Integer autoReceiveOrder = Integer.parseInt(startOnLoadService.dictionaryMap().get("AUTORECEIVEORDER"));
		/**
		 * u_id:用户名----1：用户真实姓名，手机号 2：默认收货地址 c_ids:购物车ids---商品放到购物车的记录
		 * -----店铺名+商品 -----计算总的价格出来--需要再比对一次 收获地址：address:id 备注：remark
		 * 付款方式：payType 0:余额支付 1:支付宝 2:微信 3:货到付款 优惠券：------暂时先不写 配送费：sendfee
		 * 在线支付立减优惠活动---不写先--- 订单总金额 sumPrice
		 * 
		 * 需要校验：1-商品库存是否充足 2-后台计算金额与前台传过来的是否一致 多个商铺-一个商铺生成一个订单------
		 * 订单成功后，更新购物车状态，---已成单
		 * 
		 * 
		 */
		// 校验日期
		if (apiCarService.checkSendTime(orderConfirmPage, map)
				&& apiCarService.checkOrderAddress(orderConfirmPage, map)) {
			// 保存订单信息
			// 返回：订单总额 账户余额 第三方账户还需支付
			String u_id = orderConfirmPage.getU_id();// 用户名
			Integer address_id = orderConfirmPage.getAddress_id();
			String remark = orderConfirmPage.getRemark();
			Integer payType = orderConfirmPage.getPayType();
			String sumPrice = orderConfirmPage.getSumPrice();
			BigDecimal sumPriceMoney =BigDecimal.ZERO;// 应付金额
			BigDecimal sumPriceCheck =BigDecimal.ZERO;// 校验金额
			// 根据地址id获取用户的地址
			ApiAddress addressPage = apiAddressMapper.searchAddressByid(address_id);
			String address = addressPage.getCity() + addressPage.getAddress();// 收货地址
			String name = addressPage.getName();// 收货人姓名
			String mobile = addressPage.getPhone();// 收货人电话
			String longitude = addressPage.getLongitude();// 收货地址经度
			String latitude = addressPage.getLatitude();// 收货地址纬度
			InitOrderPage orderPage = getShopListByCids(orderConfirmPage.getC_ids());
			List<CarShopPage> shopList = orderPage.getShopList();
			List<ApiDingDan> orderList = null;

			Map<Integer, String> sendTimeMap = orderConfirmPage.getSendTimeMap();

			// 优惠券
			Map<Integer, Integer> cashMap = orderConfirmPage.getCashMap();
			if (shopList != null && shopList.size() > 0) {
				List<Integer> cIdList = new ArrayList<Integer>();
				orderList = new ArrayList<ApiDingDan>();
				InitPaymentPage paymentPage = new InitPaymentPage();
				String orderIds = "";
				String orderIdFlag = "";
				for (CarShopPage shopPage : shopList) {
					ApiDingDan apiDingDan = new ApiDingDan();

					List<Integer> carIdList = new ArrayList<Integer>();

					BigDecimal sendFee = shopPage.getSendfee();
					BigDecimal sumGoodsPrice = shopPage.getSumShopPrice();
					BigDecimal money = sendFee.add(sumGoodsPrice);
					BigDecimal discountMoney =BigDecimal.ZERO;// 优惠金额---使用优惠券的金额
					Integer shop_id = shopPage.getShop_id();
					// String sendDate = sendTimeMap.get(shop_id);
					Integer is_lunchbox = shopPage.getIs_lunchbox();// 是否启用餐盒费
					BigDecimal lunchbox_price = shopPage.getLunchbox_price();// 餐盒费单价
					Integer goodsCount = shopPage.getGoodscount();// 商品数量
					BigDecimal sum_lunchbox_price = shopPage.getSum_lunchbox_price();// 该店铺的餐盒费金额
					// System.out.println("------------------------取到的配送时间：" +
					// sendDate);
					apiDingDan.setU_id(u_id);
					apiDingDan.setShop_id(shop_id);
					// apiDingDan.setSendDate(sendDate);
					apiDingDan.setBz(remark);
					if (payType >= 0 && payType <= 3) {// 0:余额支付 1:支付宝 2:微信
														// 3:货到付款
						apiDingDan.setZf_type(payType + "");// 支付方式
					}
					List<CarOrderPage> carList = shopPage.getCarList();
					Integer is_ziying = 0;
					if (carList != null && carList.size() > 0) {
						String car_ids = "";
						String product_ids = "";
						String tel = "";
						for (CarOrderPage carPage : carList) {
							tel = tel + carPage.getGoods_id() + ",";
							product_ids = product_ids + carPage.getProduct_id() + ",";
							car_ids = car_ids + carPage.getC_id() + ",";
							is_ziying = carPage.getIs_ziying();
							apiCarService.updateCar(carPage);
							carIdList.add(carPage.getC_id());
						}
						tel = tel.substring(0, tel.length() - 1);
						product_ids = product_ids.substring(0, product_ids.length() - 1);
						car_ids = car_ids.substring(0, car_ids.length() - 1);
						apiDingDan.setTel(tel);
						apiDingDan.setProduct_ids(product_ids);
						apiDingDan.setCar_ids(car_ids);

						// String shopLongitude = carList.get(0).getLongitude();
						// String shopLatitude = carList.get(0).getLatitude();
						// double to_user_distence = Utils.GetDistance(latitude,
						// longitude, shopLatitude, shopLongitude);
						// 根据city_id 判断该城市的配送距离
						// apiDingDan.setTo_user_distence(to_user_distence);
					}
					ApiT_city city = cityMapper.findT_cityById(carList.get(0).getCity_id());
					String titles = Utils.getDingDanNo(city.getU_name());
					apiDingDan.setTitles(titles);

					apiDingDan.setSerialFlagNo(titles);

					apiDingDan.setAddress(address);
					apiDingDan.setName(name);
					apiDingDan.setMobile(mobile);
					apiDingDan.setLatitude(latitude);
					apiDingDan.setLongitude(longitude);
					apiDingDan.setZi_status(0);// 0:已下单未支付 1:已支付 2:已退款
					apiDingDan.setEnable(1);// 1： 已下订单 2送餐员领取任务 3 用户未领取 4用户已领取 5
											// 订单完成 6订单因故未完成 原因 9删除
					// 判断是否1元购商品
					Integer orderType = 0;
					List<ApiCar> list = apiCarMapper.checkOneGoods(carIdList);
					System.out.println(list);
					if (list != null && list.size() > 0) {
						orderType = 4;// 1元购订单-新人特惠
					}
					apiDingDan.setOrderType(orderType);// 0-购物订单 1-充值订单 4-1元购
					apiDingDan.setAppdate(new Date());
					/**
					 * 物流状态：根据是否自营 非自营：1-商家未确认 自营：数据库配置开关-是否自动接单 1-自动接单 0-待商家确认
					 * 1:商户未确认 2:商户确认接受订单 3:等待配送接单 4:配送确认接受订单 5:配送取货成功(配送中)
					 * 6:用户确认收货 7:退货
					 */
					Integer dd_status = 1;
					if (0 == is_ziying) {// 非自营--商家待接单
						dd_status = 1;
					} else {
						// 自营--判断开关
						if (autoReceiveOrder == 1) {// 自动接单
							dd_status = 2;
						} else {
							dd_status = 1;
						}
					}
					apiDingDan.setDd_status(dd_status);// 1-商家未确认
					apiDingDan.setIs_quan(0);// 未使用优惠券

					// 使用优惠券的判断
					// if (cashMap != null && cashMap.size() > 0) {// 使用优惠券
					// if (cashMap.containsKey(shopPage.getShop_id())) {//
					// 该店铺使用了优惠券
					// apiDingDan.setIs_quan(1);// 使用优惠券
					// Integer quan_id = cashMap.get(shopPage.getShop_id());
					// apiDingDan.setQuan_id(quan_id);
					// // 将优惠券标记为已使用
					// ApiJuan juan = apiJuanMapper.selectJuanByCid(quan_id);
					// discountMoney = juan.getCashed();
					// // 标记优惠券为已使用
					// // 根据优惠券id 和用户id查询该用户的优惠券
					// ApiT_juan_tj juan_tj =
					// apiJuanTJMapper.selectApiT_juan_tjByUidAndJid(u_id,
					// quan_id);
					// Integer count = juan_tj.getCount() - 1;
					// juan_tj.setCount(count);
					// if (count > 0) {
					// juan_tj.setEnable(0);// 优惠券已使用,但数量大于0，可继续使用
					// } else {
					// juan_tj.setEnable(1);// 优惠券已使用
					// }
					//
					// apiJuanTJMapper.updateApiT_juan_tj(juan_tj);
					// }
					// }
					
					orderList.add(apiDingDan);
					Integer is_send = 1;
					String shopLongitude = carList.get(0).getLongitude();
					String shopLatitude = carList.get(0).getLatitude();
					
					// double to_user_distence = Utils.GetDistance(latitude,
					// longitude, shopLatitude, shopLongitude);
					// System.out.println("商家到配送端的距离：" + to_user_distence);
					// if(!Util.isNull(city.getSend_distance()) &&
					// to_user_distence>city.getSend_distance()){//超出配送距离
					// sendFee = 0.0;
					// is_send = 0;
					// }-----不校验距离，下订单前已校验

					apiDingDan.setSumGoodsPrice(sumGoodsPrice);
					apiDingDan.setSendFee(sendFee);
					apiDingDan.setMoney(sendFee.add(sumGoodsPrice));// 订单总金额 未优惠前的
					apiDingDan.setPayMoney(sendFee.add(sumGoodsPrice).subtract(discountMoney));// 应付金额，优惠后的
					apiDingDan.setIs_send(is_send);
					apiDingDan.setOrderNum(apiDingDanMapper.searchMaxOrderNumByShopId(shop_id)+"");
					if (1 == is_lunchbox) {
						apiDingDan.setIs_lunchbox(is_lunchbox);
						apiDingDan.setLunchbox_price(lunchbox_price);
						apiDingDan.setGoodscount(goodsCount);
						apiDingDan.setSum_lunchbox_price(sum_lunchbox_price);
					}

					apiDingDanMapper.saveDingDan(apiDingDan);// -
																// -------------保存订单

					sumPriceCheck = sumPriceCheck.add(money);// 用于校验订单金额
					sumPriceMoney = sumPriceMoney.add(apiDingDan.getPayMoney());

					orderIds = orderIds + titles + ",";
					if ("".equals(orderIdFlag)) {
						orderIdFlag = apiDingDan.getTitles();
					}
					// 赋值id
					if (carList != null && carList.size() > 0) {
						for (CarOrderPage carPage : carList) {
							ApiDingAss dingAss = new ApiDingAss();
							dingAss.setDid(apiDingDan.getRid());
							dingAss.setRid(carPage.getGoods_id());
							dingAss.setProduct_id(carPage.getProduct_id());
							dingAss.setMoney(carPage.getPrice());
							dingAss.setNum(carPage.getCount());
							cIdList.add(carPage.getC_id());// --------购物单ids
							// 保存订单详细：
							apiDingAssMapper.saveDingAss(dingAss);
						}
					}

					logger.info("订单号：" + titles + "--订单总金额：" + money + "--应付金额：" + apiDingDan.getPayMoney());
					/** 消息推送，每次新产生订单，给商家推送消息 */
					/** 新订单-不是自动接单，且是货到付款或是已付款 */
					// apiTOrderMessageService.sendShopNewOrderMessage(apiDingDan);
					// // 生成订单后，商家已接单，添加配送任务---未付款的还没有配送任务
					// apiT_shippingService.produceSendTask(apiDingDan);

				}
				// carparams.put("status", 2);// 2-已成单 0-正常 1-删除----在上面1条1条更新
				// carparams.put("cIds", cIdList);
				// // 订单生成后，更新购物车记录，插入表t_dingass表订单信息
				// apiCarMapper.modifyCarInfo(carparams);
				orderIds = orderIds.substring(0, orderIds.length() - 1);//用于生成支付的支付号
				logger.info("传入总金额：" + sumPrice + "-----后台计算总金额" + sumPriceCheck);

				ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
				paymentPage.setU_id(u_id);
				paymentPage.setCmoney(member.getCmoney());
				paymentPage.setSumPrice(sumPriceMoney);
				paymentPage.setOrderIds(orderIds);
				paymentPage.setOrderIdFlag(orderIdFlag);
				
				map.put("datas", paymentPage);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "success");
			} else {
				map.put(Utils.RESULT, "-1111");
				map.put(Utils.MESSAGE, "购物记录不存在，请返回选择！");
			}
		}

	}

	@Override
	public void getChargeCondition(Map<String, String> params, Map<String, Object> map) throws Exception {
		String u_id = params.get("u_id");
		String type = params.get("type");// 类型：1-充值记录 2-消费记录
		Integer pageCount = Integer.parseInt(params.get("pageCount"));
		PageInfo page = new PageInfo();
		page.setCurrentPage(pageCount);

		// 消费记录---使用余额，支付成功，商铺名+图片，订单时间，
		// 充值记录-----两个都返回
		InitAccountPage initAccountPage = new InitAccountPage();
		List<AccountPage> list = new ArrayList<AccountPage>();
		if ("1".equals(type)) {// 充值记录
			list = apiDingDanMapper.searchReChargeOrdersListPage(u_id, page);
		} else {
			list = apiDingDanMapper.searchConsumeOrdersListPage(u_id, page);
		}

		initAccountPage.setList(list);
		initAccountPage.setTotalPage(page.getTotalPage());

		map.put("datas", initAccountPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	@Override
	public void getMyOrders(Map<String, String> params, Map<String, Object> map, PageInfo page) throws Exception {
		String u_id = params.get("u_id");
		String orderStatus = params.get("orderStatus");// 0-正处理，1-已完成，2-已取消
		/**
		 * 订单状态--1： 已下订单 2客户取消 3 申请退货 4商家取消 5 订单完成 6订单因故未完成 原因 支付状态 0:已下单未支付
		 * 1:已支付 2:已退款 物流状态： 1:商户未确认 2:商户确认接受订单 3:等待配送接单 4:配送确认接受订单
		 * 5:配送取货成功(配送中) 6:用户确认收货 7:退货
		 */
		Map<String, Object> paramData = new HashMap<String, Object>();
		List<MyOrderPage> handingOrders = null;
		List<MyOrderPage> completeOrders = null;
		List<MyOrderPage> cancelOrders = null;
		List<MyOrderPage> myOrders = null;
		/** 获取处理中的订单 enable=1 */
		if ("0".equals(orderStatus)) {
			paramData.put("u_id", u_id);
			List<Integer> enableList = new ArrayList<Integer>();
			enableList.add(1);
			paramData.put("list", enableList);
			myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		}
		/** 获取已完成的订单 */
		if ("1".equals(orderStatus)) {
			paramData.put("u_id", u_id);
			List<Integer> enableList = new ArrayList<Integer>();
			enableList.add(5);
			paramData.put("list", enableList);
			myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		}

		/** 获取取消的订单 enable=2 || enable=4 */
		if ("2".equals(orderStatus)) {
			paramData.put("u_id", u_id);
			List<Integer> enableList = new ArrayList<Integer>();
			enableList.add(2);
			enableList.add(4);
			paramData.put("list", enableList);
			myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		}
		// goodsList-----赋值---根据goods——ids 查询商品列表
		if (myOrders != null && myOrders.size() > 0) {
			for (MyOrderPage orderPage : myOrders) {
				// List<GoodsPage> goodsList = new ArrayList<GoodsPage>();
				// goodsList =
				// apiGoodsService.searchGoodsByGoodsIds(orderPage.getDid(),
				// orderPage.getTel());
				// orderPage.setGoodsList(goodsList);
				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				// 判断订单状态-------区分自营、非自营
				apiCommonService.setOrderShowStatus(orderPage);
			}
		}

		InitMyOrderPage initMyOrderPage = new InitMyOrderPage();
		initMyOrderPage.setHandingOrders(handingOrders);
		initMyOrderPage.setCompleteOrders(completeOrders);
		initMyOrderPage.setCancelOrders(cancelOrders);
		initMyOrderPage.setMyOrders(myOrders);
		initMyOrderPage.setTotalPage(page.getTotalPage());
		map.put("page", page);
		map.put("datas", initMyOrderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/***
	 * 用户端 我的订单 (B2B不含020配送)
	 ***/
	public void getMyOrderInfos(Map<String, String> params, Map<String, Object> map, PageInfo page) {
		String u_id = params.get("u_id");
		String orderStatus = params.get("orderStatus");// 0-正处理，1-已完成，2-已取消
		/**
		 * 订单状态--1： 已下订单 2客户取消 3 申请退货 4商家取消 5 订单完成 6订单因故未完成 原因 支付状态 0:已下单未支付
		 * 1:已支付 2:已退款 物流状态： 1:商户未确认 2:商户确认接受订单 3:等待配送接单 4:配送确认接受订单
		 * 5:配送取货成功(配送中) 6:用户确认收货 7:退货
		 */
		Map<String, Object> paramData = new HashMap<String, Object>();
		Integer handingOrdersNum = 0;
		Integer completeOrdersNum = 0;
		Integer cancelOrdersNum = 0;
		List<MyOrderPage> myOrders = null;
		List<MyOrderPage> result = null;
		/** 获取处理中的订单 enable=1 */
		paramData.put("u_id", u_id);
		List<Integer> enableList = new ArrayList<Integer>();
		enableList.add(1);
		paramData.put("list", enableList);
		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		handingOrdersNum = myOrders.size();
		if ("0".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取已完成的订单 */
		enableList.clear();
		enableList.add(5);
		paramData.put("list", enableList);
		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		completeOrdersNum = myOrders.size();
		if ("1".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取取消的订单 enable=2 || enable=4 */
		enableList.clear();
		enableList.add(2);
		enableList.add(4);
		paramData.put("list", enableList);
		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		cancelOrdersNum = myOrders.size();
		if ("2".equals(orderStatus)) {
			result = myOrders;
		}
		// goodsList-----赋值---根据goods——ids 查询商品列表
		if (result != null && result.size() > 0) {
			for (MyOrderPage orderPage : result) {
				// List<GoodsPage> goodsList = new ArrayList<GoodsPage>();
				// goodsList =
				// apiGoodsService.searchGoodsByGoodsIds(orderPage.getDid(),
				// orderPage.getTel());
				// orderPage.setGoodsList(goodsList);
				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				// 判断订单状态-------区分自营、非自营
				apiCommonService.setOrderShowStatus(orderPage);
			}
		}

		InitMyOrderPage2 initMyOrderPage2 = new InitMyOrderPage2();
		initMyOrderPage2.setMyOrders(result);
		// initMyOrderPage2.setCancelOrdersNum(cancelOrdersNum);
		// initMyOrderPage2.setCompleteOrdersNum(completeOrdersNum);
		// initMyOrderPage2.setHandingOrdersNum(handingOrdersNum);
		map.put("page", page);
		map.put("datas", initMyOrderPage2);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/***
	 * 获取用户端 我的订单 不关联配送
	 **/
	public void getMyAllOrderInfos(Map<String, String> params, Map<String, Object> map, PageInfo page) {
		String u_id = params.get("u_id");
		String orderStatus = params.get("orderStatus");// ""-全部；0-待支付;1-待发货;2-待收货;3-待评价
		String goodnames = params.get("goodnames");

		Map<String, Object> paramData = new HashMap<String, Object>();
		Integer allOrdersNum = 0;
		Integer noPayOrdersNum = 0;
		Integer waitsendOrdersNum = 0;
		Integer waitTakeInOrdersNum = 0;
		Integer waitDianPinOrdersNum = 0;
		List<MyOrderPage> myOrders = null;
		List<MyOrderPage> result = null;
		List<Integer> enableList = new ArrayList<Integer>();
		/** 获取所有订单 */
		paramData.put("u_id", u_id);
		if (null != goodnames && !"".equals(goodnames)) {
			paramData.put("goodnames", goodnames);
		}
		myOrders = apiDingDanMapper.searchAllOrdersListPage(paramData, page);
		allOrdersNum = page.getTotalResult();
		if ("".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取处理中的订单(未付款) enable=1 */
		paramData.put("u_id", u_id);
		enableList.add(1);// 未完成的订单
		paramData.put("list", enableList);
		paramData.put("zi_status", 0);// 未支付
		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		noPayOrdersNum = page.getTotalResult();
		if ("0".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取待发货订单 */
		paramData.put("dd_status", 1);
		paramData.put("zi_status", 1);// 已支付
		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		waitsendOrdersNum = page.getTotalResult();
		if ("1".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取待收货订单 */
		paramData.put("dd_status", 2);
		paramData.put("zi_status", 1);// 已支付
		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		waitTakeInOrdersNum = page.getTotalResult();
		if ("2".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取待评价订单 */
		myOrders = apiDingDanMapper.searchOrdersNoDianPingListPage(paramData, page);
		waitDianPinOrdersNum = page.getTotalResult();
		if ("3".equals(orderStatus)) {
			result = myOrders;
		}

		// goodsList-----赋值---根据goods——ids 查询商品列表
		if (result != null && result.size() > 0) {
			for (MyOrderPage orderPage : result) {
				// List<GoodsPage> goodsList = new ArrayList<GoodsPage>();
				// goodsList =
				// apiGoodsService.searchGoodsByGoodsIds(orderPage.getDid(),
				// orderPage.getTel());
				// orderPage.setGoodsList(goodsList);
				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				// 判断订单状态-------区分自营、非自营
				apiCommonService.setOrderShowStatus(orderPage);
			}
		}

		InitMyOrderPage2 initMyOrderPage2 = new InitMyOrderPage2();
		initMyOrderPage2.setMyOrders(result);
		initMyOrderPage2.setAllOrdersNum(allOrdersNum);
		initMyOrderPage2.setNoPayOrdersNum(noPayOrdersNum);
		initMyOrderPage2.setWaitsendOrdersNum(waitsendOrdersNum);
		initMyOrderPage2.setWaitTakeInOrdersNum(waitTakeInOrdersNum);
		initMyOrderPage2.setWaitDianPinOrdersNum(waitDianPinOrdersNum);
		map.put("page", page);
		map.put("datas", initMyOrderPage2);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	@Override
	public void getNoDianPingOrders(Map<String, String> params, Map<String, Object> map, PageInfo page)
			throws Exception {
		// 查询未评价的订单
		String u_id = params.get("u_id");
		Map<String, Object> paramData = new HashMap<String, Object>();
		paramData.put("u_id", u_id);
		paramData.put("enable", 5);// 已完成的订单
		List<MyOrderPage> myOrders = apiDingDanMapper.searchOrdersNoDianPingListPage(paramData, page);
		if (myOrders != null && myOrders.size() > 0) {
			for (MyOrderPage orderPage : myOrders) {
				// List<GoodsPage> goodsList = new ArrayList<GoodsPage>();
				// goodsList =
				// apiGoodsService.searchGoodsByGoodsIds(orderPage.getDid(),
				// orderPage.getTel());
				// orderPage.setGoodsList(goodsList);
				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				// //判断订单状态-------区分自营、非自营----待评价商品，不用
				// apiCommonService.setOrderShowStatus(orderPage);
			}
		}

		InitMyOrderPage initMyOrderPage = new InitMyOrderPage();
		initMyOrderPage.setMyOrders(myOrders);
		initMyOrderPage.setTotalPage(page.getTotalPage());
		map.put("page", page);
		map.put("datas", initMyOrderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/** 订单详情 */
	@Override
	public void getOrderInfo(String titles, Map<String, Object> map) {
		InitOrderInfoPage orderInfoPage = new InitOrderInfoPage();
		// 根据订单号查询订单
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(titles);
		if (dingDan != null) {
			// 商品名称---根据shop_id 获取商品信息
			ApiShop shop = apiShopsMapper.findT_shopsById(dingDan.getShop_id());

			orderInfoPage.setDingDan(dingDan);
			orderInfoPage.setShop(shop);
			Integer is_quan = dingDan.getIs_quan();
			if (is_quan != null && 1 == is_quan) {
				Integer quan_id = dingDan.getQuan_id();
				ApiJuan juan = apiJuanMapper.selectJuanByCid(quan_id);
				Double discount_money = juan.getCashed();
				dingDan.setDiscount_money(discount_money);
			} else {
				dingDan.setIs_quan(0);
				dingDan.setDiscount_money(0.0);
			}

			// 根据订单id，查询商品列表
			// List<GoodsPage> goodsList = new ArrayList<GoodsPage>();
			// goodsList =
			// apiGoodsService.searchGoodsByOrderId(dingDan.getRid());
			// orderInfoPage.setGoodsList(goodsList);
			List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
			productList = apiCarService.searchCarProductsByCids(dingDan.getCar_ids());
			orderInfoPage.setProductList(productList);

			map.put("datas", orderInfoPage);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "success");
		}
	}

	/** 订单详情 */
	@Override
	public InitOrderInfoPage getOrderInfoObj(String titles) {
		InitOrderInfoPage orderInfoPage = new InitOrderInfoPage();
		// 根据订单号查询订单
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(titles);
		if (dingDan != null) {
			// 商品名称---根据shop_id 获取商品信息
			ApiShop shop = apiShopsMapper.findT_shopsById(dingDan.getShop_id());

			orderInfoPage.setDingDan(dingDan);
			orderInfoPage.setShop(shop);
			Integer is_quan = dingDan.getIs_quan();
			if (is_quan != null && 1 == is_quan) {
				Integer quan_id = dingDan.getQuan_id();
				ApiJuan juan = apiJuanMapper.selectJuanByCid(quan_id);
				Double discount_money = juan.getCashed();
				dingDan.setDiscount_money(discount_money);
			} else {
				dingDan.setIs_quan(0);
				dingDan.setDiscount_money(0.0);
			}

			// 根据订单id，查询商品列表
			// List<GoodsPage> goodsList = new ArrayList<GoodsPage>();
			// goodsList =
			// apiGoodsService.searchGoodsByOrderId(dingDan.getRid());
			// orderInfoPage.setGoodsList(goodsList);
			List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
			productList = apiCarService.searchCarProductsByCids(dingDan.getCar_ids());
			orderInfoPage.setProductList(productList);

		}

		return orderInfoPage;
	}

	@Transactional
	@Override
	public void cancelOrder(String titles, Map<String, Object> map) {
		// 根据订单号查询订单
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(titles);
		if (dingDan != null) {
			/**
			 * 判断订单状态 0:已下单未支付 1:已支付 2:已退款
			 */
			if (0 == dingDan.getZi_status()) {// 未支付----直接取消成功
				// ----判断是否货到付款---货到付款---也不用填写原因
				// 修改订单状态---2-已取消----取消原因：未支付，直接取消
				dingDan.setEnable(2);
				dingDan.setCancelReason("未支付，直接取消!");
				// 判断是否使用优惠券，恢复其使用
				apiT_juan_tjService.recoveryJuanOnDingDan(dingDan);
				// 恢复库存数量
				//apiT_productsService.modifyProductCountByOrderId(titles);
				// 取消订单，如果已付款，退款到余额
				refundPaymoneyByCancelOrder(dingDan);

				apiDingDanMapper.updateDingDan(dingDan);
				dingDan.setEnable(9);// ------目前返回用于前台判断

				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "取消成功！");
				map.put("datas", dingDan);
			} else if (1 == dingDan.getZi_status()) {// 已支付，商家待接单---非自营的
				// 填写取消原因---订单状态：2-申请取消
				/**
				 * 1:商户未确认 2:商户确认接受订单-----申请退货（确认收货）---货未到是否申请 3:等待配送接单
				 * 4:配送确认接受订单 5:配送取货成功(配送中) 6:用户确认收货 7:退货
				 */
				if (1 == dingDan.getDd_status()) {// 商家未确认---填写取消原因
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "需要填写取消原因！");
					dingDan.setEnable(2);// 申请取消
					map.put("datas", dingDan);
					// 页面跳转
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "商家已接单，请申请退货");
				}
			}
		}
	}

	@Transactional
	@Override
	public void cancelReason(CancelReasonPage cancelReasonPage, Map<String, Object> map) {
		String titles = cancelReasonPage.getTitles();
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(titles);
		if (dingDan != null && dingDan.getDd_status() == 1) {
			dingDan.setEnable(2);// 申请取消
			dingDan.setName(cancelReasonPage.getName());
			dingDan.setMobile(cancelReasonPage.getMobile());
			dingDan.setCancelReason(cancelReasonPage.getCancelReason());
			// 判断是否使用优惠券，恢复其使用
			apiT_juan_tjService.recoveryJuanOnDingDan(dingDan);
			// 恢复库存数量
			apiT_productsService.modifyProductCountByOrderId(titles);
			// 取消订单，如果已付款，退款到余额
			refundPaymoneyByCancelOrder(dingDan);

			apiDingDanMapper.updateDingDan(dingDan);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "取消成功！");
		} else if (dingDan != null && dingDan.getDd_status() == 2) {// --上一步中已判断过已支付了，取消订单时商家接单了，提示商家已接，只能申请退货
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "商家已接单，请申请退货");
		}
	}

	@Transactional
	@Override
	public void confirmReceive(String titles, Map<String, Object> map) {
		/**
		 * 确认收货：收货时间，订单完成(状态更新 enable=5 已完成) 物流状态：dd_status:6-用户确认收货
		 */
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(titles);
		if (dingDan != null) {
			dingDan.setEnable(5);// 5-已完成
			// dingDan.setDd_status(6);// 用户确认收货
			dingDan.setTakeGoodsTime(new Date());
			apiDingDanMapper.updateDingDan(dingDan);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "确认收货成功！");
		}
	}

	/****
	 * 商家订单
	 ***/
	@Override
	public void getShopOrders(SearchOrdersPage searchOrdersPage, Map<String, Object> map) throws Exception {
		/** 返回数据组装页 */
		PageInfo page = new PageInfo();
		page.setCurrentPage(searchOrdersPage.getPageCount());// 设置要读取的页

		// 商家查询新订单---非自营商品--查询待接单的订单
		String shop_idStr = searchOrdersPage.getShop_id();
		Integer shop_id = Integer.parseInt(shop_idStr);
		Integer orderStatus = searchOrdersPage.getOrderStatus();
		Integer is_clothes = apiShopsService.checkShopIsClothes(shop_id);

		/**
		 * orderStatus:0-新订单----待商家确认接单 非自营（没有退货） 9-全部订单-根据订单状态查询（不包括待接单的）---
		 * 1-待配送接单---- 2-配送中的订单--- 3-用户已确认的订单(确认收货)-- 4-取消的订单--- --配送状态-根据配送状态查询
		 * 5-待配送员接单-- 6-配送员取单中-- 7-配送员送货中-- 8-配送员货送达-- 商铺端的订单： 9,全部的订单：待接单的不显示
		 * -----查询条件：配送任务表有数据的 0,待接单的订单：接单，取消 -----查询条件： dd_status=1&&( (
		 * zf_type!=3 && zi_status=1) || zf_type=3) 已接单：产生配送任务，接完单之后，订单不允许取消
		 * 
		 * 订单状态：（非自营没有退货）---从订单角度查询 1,待配送的订单：未分派+已分派配送员未接单的 -----查询条件：enable=1
		 * && (dd_status=2 || dd_status=3) -----按物流查：status=0 || status=1
		 * 2,配送中的订单：配送员接单配送中 ---查出来再判断 -----查询条件：enable!=2 && dd_status!=1
		 * -----按物流查：status=2 || status=3 || status=4 || status=5
		 * 3,用户已确认的订单：用户确认收货 -----查询条件：enable=5， -----按物流查：status=6 并不能确定用户确认收货
		 * 不可行 4,取消的订单：商家取消的订单 -----查询条件：enable=4
		 * 
		 * 物流状态：------从物流状态查询(已到物流表说明商家已接单：在线支付已支付 + 货到付款) 5,待配送员接单：已分派配送员未接单
		 * -----查询条件：status=1 6,配送员取货中：配送员接单未取货成功 -----查询条件：status=2 || status=3
		 * 7,配送员送货中：配送员取货成功 -----查询条件：status=4 || status=5 8,配送员货已送达：配送员货已送达
		 * -----查询条件：status=6
		 */
		List<MyOrderPage> shopOrders = new ArrayList<MyOrderPage>();
		Map<String, Object> params = new HashMap<String, Object>();
		String searchDate = searchOrdersPage.getSearchDate();
		if (!Util.isNull(searchDate)) {
			params.put("date", searchDate);
		}
		params.put("shop_id", shop_id);

		if (9 == orderStatus) {//
			/** 未接单的不显示，查询配送任务表的 */
			shopOrders = apiDingDanMapper.shopSearchOrdersByShopidListPage(params, page);
		}

		if (0 == orderStatus) {// 0-待接单的订单---商家未确认
			params.put("dd_status", 1);
			shopOrders = apiDingDanMapper.shopSearchNewOrdersListPage(params, page);
		}
		if (1 == orderStatus) {// 1-待配送接单 status=0,1
			List<Integer> statusList = new ArrayList<Integer>();
			statusList.add(0);
			statusList.add(1);
			params.put("list", statusList);
			shopOrders = apiDingDanMapper.shopSearchOrdersByStatusListListPage(params, page);

		}
		if (2 == orderStatus) {// 2-配送中的订单 status=2,3,4,5
			List<Integer> statusList = new ArrayList<Integer>();
			statusList.add(4);
			statusList.add(5);
			params.put("list", statusList);
			shopOrders = apiDingDanMapper.shopSearchOrdersByStatusListListPage(params, page);

		}
		if (3 == orderStatus) {// 3-用户已确认的订单(确认收货) enable=5
			List<Integer> enableList = new ArrayList<Integer>();
			enableList.add(5);
			params.put("list", enableList);
			shopOrders = apiDingDanMapper.shopSearchOrdersByEnableListPage(params, page);
		}
		if (4 == orderStatus) {// 4-取消的订单---***enable=2,4(已取消) --商家取消只查看4
			List<Integer> enableList = new ArrayList<Integer>();
			enableList.add(4);
			params.put("list", enableList);
			shopOrders = apiDingDanMapper.shopSearchOrdersByEnableListPage(params, page);
		}
		if (5 == orderStatus) {// 5-待配送员接单---status=1
			List<Integer> statusList = new ArrayList<Integer>();
			statusList.add(1);
			params.put("list", statusList);
			shopOrders = apiDingDanMapper.shopSearchOrdersByStatusListListPage(params, page);
		}
		if (6 == orderStatus) {// 6-配送员取单中---status=2,3
			List<Integer> statusList = new ArrayList<Integer>();
			statusList.add(2);
			statusList.add(3);
			params.put("list", statusList);
			shopOrders = apiDingDanMapper.shopSearchOrdersByStatusListListPage(params, page);
		}
		if (7 == orderStatus) {// 7-配送员送货中---status=4,5
			List<Integer> statusList = new ArrayList<Integer>();
			statusList.add(4);
			statusList.add(5);
			params.put("list", statusList);
			shopOrders = apiDingDanMapper.shopSearchOrdersByStatusListListPage(params, page);
		}
		if (8 == orderStatus) {// 8-配送员货送达---status=6
			List<Integer> statusList = new ArrayList<Integer>();
			statusList.add(6);
			params.put("list", statusList);
			shopOrders = apiDingDanMapper.shopSearchOrdersByStatusListListPage(params, page);
		}

		// goodsList-----赋值---根据goods——ids 查询商品列表
		if (shopOrders != null && shopOrders.size() > 0) {
			for (MyOrderPage orderPage : shopOrders) {

				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				// 判断订单状态-------区分自营、非自营
				orderPage.setShopStatus(orderStatus);
				orderPage.setIs_clothes(is_clothes);
				/**
				 * 商铺端订单的几种显示状态： 0,订单已处理，待接单-----0(接单，取消) 1,订单已处理，待配送
				 * --待配送员接单------1,5,2 2,订单已处理，待配送 --配送员取货中------6,2 3,配送中的订单
				 * --配送员送货中------7 4,用户已确认的订单
				 * --配送员已送达------3,8==这里认为用户会确认，否则物流状态会留有空白：中断-之后无法操作 5,商家已取消的订单
				 * --已取消的订单------4
				 * 
				 * status 0：未派单 1：已派单 2：已抢单 3: 已到商家 4：取货 5: 货已送出 6：货已送达
				 */
				if (0 == orderStatus) {// 如果是新订单--待接单
					orderPage.setShopStatus(0);
				} else if (0 == orderStatus) {// 已取消
					orderPage.setShopStatus(5);
				} else {
					Integer status = orderPage.getStatus();
					if (!Util.isNull(status)) {
						if (0 == status || 1 == status) {
							orderPage.setShopStatus(1);// 待配送员接单
						} else if (2 == status || 3 == status) {
							orderPage.setShopStatus(2);// 配送员取货中
						} else if (4 == status || 5 == status) {
							orderPage.setShopStatus(3);// 配送员送货中
						} else if (6 == status) {
							orderPage.setShopStatus(4);// 配送员货已送达
						}
					}
				}
			}
		}

		InitShopOrderPage initShopOrderPage = new InitShopOrderPage();
		initShopOrderPage.setShopOrders(shopOrders);
		initShopOrderPage.setTotalPage(page.getTotalPage());
		map.put("page", page);
		map.put("datas", initShopOrderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/****
	 * 商家订单 (B2B不含020配送)
	 ***/
	public void getShopOrderInfos(SearchOrdersPage searchOrdersPage, Map<String, Object> map, PageInfo page) {
		String s_id = searchOrdersPage.getShop_id().toString();
		String orderStatus = searchOrdersPage.getOrderStatus().toString();// ""-全部；-1
																			// -待支付;1-待发货;2-待收货;3-待评价
		String goodnames = searchOrdersPage.getGoodnames();

		Map<String, Object> paramData = new HashMap<String, Object>();
		Integer allOrdersNum = 0;
		Integer noPayOrdersNum = 0;
		Integer waitsendOrdersNum = 0;
		Integer waitTakeInOrdersNum = 0;
		Integer waitDianPinOrdersNum = 0;
		List<MyOrderPage> myOrders = null;
		List<MyOrderPage> result = null;
		List<Integer> enableList = new ArrayList<Integer>();
		/** 获取所有订单 */
		paramData.put("s_id", s_id);
		if (null != goodnames && !"".equals(goodnames)) {
			paramData.put("goodnames", goodnames);
		}
		myOrders = apiDingDanMapper.searchAllOrdersListPage(paramData, page);
		allOrdersNum = page.getTotalResult();
		if ("-1".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取处理中的订单(未付款) enable=1 */
		paramData.put("s_id", s_id);
		enableList.add(1); // 未完成的订单
		paramData.put("list", enableList);
		paramData.put("zi_status", 0);// 未支付

		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);

		noPayOrdersNum = page.getTotalResult();
		if ("0".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取待发货订单 */
		paramData.put("dd_status", 1);
		paramData.put("zi_status", 1);// 已支付
		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		waitsendOrdersNum = page.getTotalResult();
		if ("1".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取待收货订单 */
		paramData.put("dd_status", 2);
		paramData.put("zi_status", 1);// 已支付
		myOrders = apiDingDanMapper.searchOrdersByEnableListPage(paramData, page);
		waitTakeInOrdersNum = page.getTotalResult();
		if ("2".equals(orderStatus)) {
			result = myOrders;
		}

		/** 获取待评价订单 */
		myOrders = apiDingDanMapper.searchOrdersNoDianPingListPage(paramData, page);
		waitDianPinOrdersNum = page.getTotalResult();
		if ("3".equals(orderStatus)) {
			result = myOrders;
		}

		// goodsList-----赋值---根据goods——ids 查询商品列表
		if (result != null && result.size() > 0) {
			for (MyOrderPage orderPage : result) {

				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				// 判断订单状态-------区分自营、非自营
				apiCommonService.setOrderShowStatus(orderPage);
			}
		}

		InitMyOrderPage2 initMyOrderPage2 = new InitMyOrderPage2();
		initMyOrderPage2.setMyOrders(result);
		initMyOrderPage2.setAllOrdersNum(allOrdersNum);
		initMyOrderPage2.setNoPayOrdersNum(noPayOrdersNum);
		initMyOrderPage2.setWaitsendOrdersNum(waitsendOrdersNum);
		initMyOrderPage2.setWaitTakeInOrdersNum(waitTakeInOrdersNum);
		initMyOrderPage2.setWaitDianPinOrdersNum(waitDianPinOrdersNum);

		map.put("page", page);
		map.put("datas", initMyOrderPage2);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "成功");
	}

	/**
	 * 商家催单的列表
	 */
	@Override
	public void getRemindOrder(SearchOrdersPage searchOrdersPage, Map<String, Object> map) throws Exception {
		/** 返回数据组装页 */
		PageInfo page = new PageInfo();
		page.setCurrentPage(searchOrdersPage.getPageCount());// 设置要读取的页
		// 商家查询新订单---非自营商品--查询待接单的订单
		String shop_idStr = searchOrdersPage.getShop_id();
		Integer shop_id = Integer.parseInt(shop_idStr);
		Integer is_clothes = apiShopsService.checkShopIsClothes(shop_id);
		List<MyOrderPage> shopOrders = new ArrayList<MyOrderPage>();
		shopOrders = apiDingDanMapper.searchOrdersByReminderListPage(shop_id, page);

		// goodsList-----赋值---根据goods——ids 查询商品列表
		if (shopOrders != null && shopOrders.size() > 0) {
			for (MyOrderPage orderPage : shopOrders) {
				// List<GoodsPage> goodsList = new ArrayList<GoodsPage>();
				// goodsList =
				// apiGoodsService.searchGoodsByGoodsIds(orderPage.getDid(),
				// orderPage.getTel());
				// orderPage.setGoodsList(goodsList);
				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				orderPage.setIs_clothes(is_clothes);
				Integer dd_status = orderPage.getLogisticsStatus();

				if (1 == dd_status) {
					orderPage.setShopStatus(0);// 新订单
				} else {
					orderPage.setShopStatus(1);// 待配送员接单
				}

			}
		}

		InitShopOrderPage initShopOrderPage = new InitShopOrderPage();
		initShopOrderPage.setShopOrders(shopOrders);
		initShopOrderPage.setTotalPage(page.getTotalPage());
		map.put("datas", initShopOrderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/** 确认接单 */
	@Transactional
	@Override
	public void receiveOrder(ShopOrderPage shopOrderPage, Map<String, Object> map) throws Exception {
		String orderId = shopOrderPage.getOrderId();
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(orderId);
		if (dingDan != null) {// 确认接单，产生配送任务
			dingDan.setDd_status(2);// 2-商家确认接受订单
			apiDingDanMapper.updateDingDan(dingDan);

			// 配送任务
			apiT_shippingService.produceSendTask(dingDan);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "接单成功！");
		}
	}

	/** 拒绝接单 */
	@Transactional
	@Override
	public void refuseOrder(ShopOrderPage shopOrderPage, Map<String, Object> map) throws Exception {
		String orderId = shopOrderPage.getOrderId();
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(orderId);
		if (dingDan != null) {
			/** 后台根据是否已付款 去退款 */
			dingDan.setEnable(4);// ==4的，需要e点到家退款给客户 ==2的也需要e点到家退款
			dingDan.setCancelReason(shopOrderPage.getCancelReason());
			// 退款，后台控制，

			// 判断是否使用优惠券，恢复其使用
			apiT_juan_tjService.recoveryJuanOnDingDan(dingDan);
			// 恢复库存数量
			apiT_productsService.modifyProductCountByOrderId(orderId);
			// 取消订单，如果已付款，退款到余额
			refundPaymoneyByCancelOrder(dingDan);

			apiDingDanMapper.updateDingDan(dingDan);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "取消成功！");
		}
	}

	@Override
	public void getSendOrders(SearchOrdersPage searchOrdersPage, Map<String, Object> map) throws Exception {
		/** 返回数据组装页 */
		PageInfo page = new PageInfo();
		page.setCurrentPage(searchOrdersPage.getPageCount());// 设置要读取的页

		String u_id = searchOrdersPage.getU_id();// 配送id
		Integer orderStatus = searchOrdersPage.getOrderStatus();

		List<MyOrderPage> sendOrders = new ArrayList<MyOrderPage>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user_id", u_id);
		String searchDate = searchOrdersPage.getSearchDate();
		if (!Util.isNull(searchDate)) {
			params.put("date", searchDate);
		}

		/**
		 * orderStatus:订单状态 9-全部订单 0-未完成----status= 1-已完成
		 */

		/**
		 * sendStatus:1----待配送的订单 待接单 接单 status=1 2----待配送的订单 待取货 已到商家 status=2
		 * 3----待配送的订单 取货中 取货成功 status=3 4----配送中的订单 配送中 货已送达 status=4,5
		 * 5----已完成的订单 已完成 status=6
		 */
		/** 物流状态 status 0：未派单 1：已派单(未接单) 2：已接单 3: 已到商家 4：取货 5: 货已送出 6：货已送达 */
		if (!Util.isNull(orderStatus)) {
			if (0 == orderStatus) {
				List<Integer> statusList = new ArrayList<Integer>();
				statusList.add(1);// 未接单
				statusList.add(2);// 已接单
				statusList.add(3);// 已到商家
				statusList.add(4);// 取货
				statusList.add(5);// 货已送出
				params.put("list", statusList);
				sendOrders = apiDingDanMapper.searchSendOrdersByStatusListListPage(params, page);
			}
			if (1 == orderStatus) {
				List<Integer> statusList = new ArrayList<Integer>();
				statusList.add(6);// 货已送达
				params.put("list", statusList);
				sendOrders = apiDingDanMapper.searchSendOrdersByStatusListListPage(params, page);
			}

			// goodsList-----赋值---根据goods——ids 查询商品列表
			if (sendOrders != null && sendOrders.size() > 0) {
				for (MyOrderPage orderPage : sendOrders) {

					List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
					productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
					orderPage.setProductList(productList);
					orderPage.setIs_clothes(apiShopsService.checkShopIsClothes(orderPage.getShop_id()));
					// 判断订单状态--
					if (1 == orderPage.getStatus()) {// 1待接单 接单 status=1
						orderPage.setSendStatus(1);
					} else if (2 == orderPage.getStatus()) {// 2待取货 已到商家
															// status=2
						orderPage.setSendStatus(2);
					} else if (3 == orderPage.getStatus()) {// 3取货中 取货成功
															// status=3
						orderPage.setSendStatus(3);
					} else if (4 == orderPage.getStatus() || 5 == orderPage.getStatus()) {// 4配送中
																							// 货已送达
																							// status=4,5
						orderPage.setSendStatus(4);
					} else if (6 == orderPage.getStatus()) {// 5已完成 status=6
						orderPage.setSendStatus(5);

						// 订单的评价---货已送达才评价---商品评价+配送评价
						// 根据订单号查询商品评价
						List<ApiDianPing> dianPingList = apiDianPingMapper
								.searchDianPingByOrderid(orderPage.getTitles());
						if (dianPingList != null && dianPingList.size() > 0) {
							orderPage.setGoodsGrade(dianPingList.get(0).getC_dtype());// 几星评价
						}

						// 配送评价--根据订单号--查物流表
						ApiT_shipping shipping = apiT_shippingMapper.findT_shippingByOrderId(orderPage.getTitles());
						if (shipping != null) {
							orderPage.setSendGrade(shipping.getShipping_remark());
						}
					}
				}
			}

			InitSendOrderPage initSendOrderPage = new InitSendOrderPage();
			initSendOrderPage.setSendOrders(sendOrders);
			initSendOrderPage.setTotalPage(page.getTotalPage());
			map.put("datas", initSendOrderPage);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "success");
		}
	}

	/** 配送员接单 */
	@Transactional
	@Override
	public void sendReceiveOrders(SendOrderPage sendOrderPage, Map<String, Object> map) throws Exception {
		String u_id = sendOrderPage.getU_id();
		String orderId = sendOrderPage.getOrderId();
		// 根据订单号--查询配送--更新物流表物流状态
		ApiT_shipping shipping = apiT_shippingMapper.findT_shippingByOrderId(orderId);
		if (shipping != null) {
			shipping.setStatus(2);// 已接单
			shipping.setReceive_order_time(new Date());
			apiT_shippingMapper.updateT_shipping(shipping);

			// 更新订单表物流状态
			ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(orderId);
			dingDan.setDd_status(4);// 配送员确认接受订单
			apiDingDanMapper.updateDingDan(dingDan);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "接单成功！");
		}

	}

	/** 配送员查询订单-搜索 */
	@Override
	public void sendSearchOrders(SearchOrdersPage searchOrdersPage, Map<String, Object> map) throws Exception {

		/** 返回数据组装页 */
		PageInfo page = new PageInfo();
		page.setCurrentPage(searchOrdersPage.getPageCount());// 设置要读取的页

		String u_id = searchOrdersPage.getU_id();
		String conditions = searchOrdersPage.getConditions();// 搜索条件，可能是订单号(模糊匹配)、地址(模糊匹配)

		List<MyOrderPage> sendOrders = new ArrayList<MyOrderPage>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user_id", u_id);
		params.put("conditions", conditions);

		String searchDate = searchOrdersPage.getSearchDate();
		if (!Util.isNull(searchDate)) {
			params.put("date", searchDate);
		}

		sendOrders = apiDingDanMapper.sendSearchOrdersListPage(params, page);

		// goodsList-----赋值---根据goods——ids 查询商品列表
		if (sendOrders != null && sendOrders.size() > 0) {
			for (MyOrderPage orderPage : sendOrders) {

				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				orderPage.setIs_clothes(apiShopsService.checkShopIsClothes(orderPage.getShop_id()));
				// 判断订单状态--
				if (1 == orderPage.getStatus()) {// 1待接单 接单 status=1
					orderPage.setSendStatus(1);
				} else if (2 == orderPage.getStatus()) {// 2待取货 已到商家 status=2
					orderPage.setSendStatus(2);
				} else if (3 == orderPage.getStatus()) {// 3取货中 取货成功 status=3
					orderPage.setSendStatus(3);
				} else if (4 == orderPage.getStatus() || 5 == orderPage.getStatus()) {// 4配送中
																						// 货已送达
																						// status=4,5
					orderPage.setSendStatus(4);
				} else if (6 == orderPage.getStatus()) {// 5已完成 status=6
					orderPage.setSendStatus(5);
				}
			}
		}

		InitSendOrderPage initSendOrderPage = new InitSendOrderPage();
		initSendOrderPage.setSendOrders(sendOrders);
		initSendOrderPage.setTotalPage(page.getTotalPage());
		map.put("datas", initSendOrderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	@Override
	public void shopSearchOrders(SearchOrdersPage searchOrdersPage, Map<String, Object> map) throws Exception {
		/** 返回数据组装页 */
		PageInfo page = new PageInfo();
		page.setCurrentPage(searchOrdersPage.getPageCount());// 设置要读取的页

		String shop_id = searchOrdersPage.getShop_id();
		String conditions = searchOrdersPage.getConditions();// 搜索条件，可能是订单号(模糊匹配)、地址(模糊匹配)
		Integer is_clothes = apiShopsService.checkShopIsClothes(Integer.valueOf(shop_id));

		List<MyOrderPage> shopOrders = new ArrayList<MyOrderPage>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("shop_id", shop_id);
		params.put("conditions", conditions);
		shopOrders = apiDingDanMapper.shopSearchOrdersListPage(params, page);

		// goodsList-----赋值---根据goods——ids 查询商品列表
		if (shopOrders != null && shopOrders.size() > 0) {
			for (MyOrderPage orderPage : shopOrders) {
				// List<GoodsPage> goodsList = new ArrayList<GoodsPage>();
				// goodsList =
				// apiGoodsService.searchGoodsByGoodsIds(orderPage.getDid(),
				// orderPage.getTel());
				// orderPage.setGoodsList(goodsList);
				List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
				productList = apiCarService.searchCarProductsByCids(orderPage.getCar_ids());
				orderPage.setProductList(productList);
				orderPage.setIs_clothes(is_clothes);
				// 判断订单状态-------区分自营、非自营
				if (9 == orderPage.getEnable() || 4 == orderPage.getEnable()) {// 已取消订单
					orderPage.setShopStatus(4);
				} else if (2 == orderPage.getLogisticsStatus()) {// 2-商家确认接单
					orderPage.setShopStatus(1);
				} else if (3 == orderPage.getLogisticsStatus()) {// 3-待配送接单
					orderPage.setShopStatus(5);
				} else if (4 == orderPage.getLogisticsStatus()) {// 4-配送确认接受订单
					orderPage.setShopStatus(6);
				} else if (5 == orderPage.getLogisticsStatus()) {// 5-配送取货成功
					orderPage.setShopStatus(7);
				} else if (6 == orderPage.getLogisticsStatus()) {// 6-客户确认收货
					orderPage.setShopStatus(8);
				}
			}
		}

		InitShopOrderPage initShopOrderPage = new InitShopOrderPage();
		initShopOrderPage.setShopOrders(shopOrders);
		initShopOrderPage.setTotalPage(page.getTotalPage());
		map.put("page", page);
		map.put("datas", initShopOrderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/** 配送端已到商家 */
	@Transactional
	@Override
	public void senderArriveShop(SendOrderPage sendOrderPage, Map<String, Object> map) throws Exception {
		String u_id = sendOrderPage.getU_id();
		String orderId = sendOrderPage.getOrderId();
		// 根据订单号--查询配送--更新物流表物流状态
		ApiT_shipping shipping = apiT_shippingMapper.findT_shippingByOrderId(orderId);
		if (shipping != null) {
			shipping.setStatus(3);// 已到商家
			shipping.setArrive_shop_time(new Date());
			apiT_shippingMapper.updateT_shipping(shipping);
		}
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "操作成功！");
	}

	/** 配送员取货成功 */
	@Transactional
	@Override
	public void senderTakeGoods(SendOrderPage sendOrderPage, Map<String, Object> map) throws Exception {
		// 取货成功 shipping：status=4(取货) dingdan dd_status=5(取货成功，配送中)
		String u_id = sendOrderPage.getU_id();
		String orderId = sendOrderPage.getOrderId();
		// 根据订单号--查询配送--更新物流表物流状态
		ApiT_shipping shipping = apiT_shippingMapper.findT_shippingByOrderId(orderId);
		if (shipping != null) {
			shipping.setStatus(4);// 取货成功
			shipping.setTake_goods_time(new Date());

			// 更新订单表物流状态----
			ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(orderId);

			// 如果是非自营店且是 ‘现结算’ 查出折扣
			ApiShop shop = apiShopsMapper.getShopByOrderId(orderId);
			BigDecimal cash_term_money =BigDecimal.ZERO;
			if (shop != null && 0 == shop.getIs_ziying() && "现结算".equals(shop.getBalance())) {
				BigDecimal discount =Util.getBigDecimal((shop.getDiscount()));
				BigDecimal sumGoodsPrice = dingDan.getSumGoodsPrice();
				cash_term_money = sumGoodsPrice .multiply(discount);

				// 账户信息--备用金不变，账户余额减少
				ApiT_shipper_account shipper_account = apiT_shipper_accountMapper.selectShipperAccountByUid(u_id);
				if (shipper_account != null) {
					BigDecimal money = shipper_account.getMoney();
					if (money == null) {
						money =BigDecimal.ZERO;
					}
					money = money .subtract(cash_term_money) ;
					shipper_account.setMoney(money);
					apiT_shipper_accountMapper.updateT_shipper_account(shipper_account);
				}
			}
			shipping.setCash_term_money(cash_term_money);// 非自营店现结算，配送员应支付商家金额

			apiT_shippingMapper.updateT_shipping(shipping);

			dingDan.setDd_status(5);// 配送员确认接受订单
			apiDingDanMapper.updateDingDan(dingDan);

			/** 配送员取货成功，通知客户订单已在配送途中 */
			apiTOrderMessageService.remindUserOrderInSending(dingDan.getU_id(), orderId);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "取货成功！");

		}
	}

	/** 配送员货已送达 */
	@Transactional
	@Override
	public void sendGoodsOut(SendOrderPage sendOrderPage, Map<String, Object> map) throws Exception {
		// 货已送达 shipping：status=5(货已送达) 货到付款方式：商品金额+配送费
		String u_id = sendOrderPage.getU_id();
		String orderId = sendOrderPage.getOrderId();
		// 根据订单号--查询配送--更新物流表物流状态
		ApiT_shipping shipping = apiT_shippingMapper.findT_shippingByOrderId(orderId);
		if (shipping != null) {
			shipping.setStatus(6);
			Date date = new Date();
			shipping.setShipping_out_time(date);// 这个字段不用
			shipping.setArrive_user_time(date);
			// 更新订单支付状态----判断是否货到付款
			ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(orderId);
			if ("3".equals(dingDan.getZf_type())) {// 货到付款---更新支付状态---增加积分
				dingDan.setZi_status(1);// 已支付
				dingDan.setPaytime(new Date());
				// 货到付款，配送员代收金额---订单应付金额+已代收金额
				ApiT_shipper_account shipperAccount = apiT_shipper_accountMapper.selectShipperAccountByUid(u_id);
				BigDecimal order_cash = dingDan.getPayMoney().add(shipperAccount.getOrder_cash());
				// 账户余额增加
				BigDecimal money = shipperAccount.getMoney().add(dingDan.getPayMoney());
				shipperAccount.setOrder_cash(order_cash);// 货到付款金额
				shipperAccount.setMoney(money);// 账户余额
				apiT_shipper_accountMapper.updateT_shipper_account(shipperAccount);
				shipping.setOn_delivery_money(dingDan.getPayMoney());

			}
			// 判断是否准时送达 根据sendDate new Date() 比较判断
			int flag = checkIsOnTime(dingDan.getSendDate(), date);
			// 衣物干洗--默认准时送达
			Integer is_clothes = apiShopsService.checkShopIsClothes(dingDan.getShop_id());
			if (1 == is_clothes) {// 是衣物干洗，默认准时送达
				flag = 0;
			}
			shipping.setIs_ontime(flag);
			apiT_shippingMapper.updateT_shipping(shipping);
			// ==客户确认收货
			dingDan.setEnable(5);// 5-已完成
			dingDan.setDd_status(6);// 用户确认收货
			dingDan.setTakeGoodsTime(new Date());
			apiDingDanMapper.updateDingDan(dingDan);

			// 给用户奖励积分
			apiT_points_ruleService.awardMemberPoints(dingDan);

			// 给客户推送消息，提醒客户对配送服务进行评价
			apiTOrderMessageService.remindUserEvaluate(dingDan.getU_id(), orderId);
			apiCommonService.autoAllocateTask();

			// 更新商品的订单下单量，购买量，销售额----在产生配送任务时记录
			// apiT_log_userService.updateGoodsOrderInfo(orderId);

			// 推荐有奖逻辑
			apiT_recommend_couponService.newLoginFirstOrder(dingDan.getU_id());

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功！");
		}
	}

	private int checkIsOnTime(String sendDate, Date date) {
		int flag = 0;// 0-准时送达 1-超时 2-早达
		// sendDate : 2015-11-10 10:00-10:30 yyyy/MM/dd HH:mm:ss
		try {
			if (!Util.isNull(sendDate)) {
				String[] timeArray = sendDate.split(" ");
				if (timeArray != null && timeArray.length > 0) {
					String firstDate = timeArray[0].trim();// 2015-11-10
					String secondDate = timeArray[1].trim();// 10:00-10:30
					String[] secondArray = secondDate.split("-");
					if (secondArray != null && secondArray.length > 0) {
						String d1 = secondArray[0] + ":00";
						String d2 = secondArray[1] + ":00";
						Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(firstDate + " " + d1);
						Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(firstDate + " " + d2);
						if (date.before(date1)) {// 早达
							flag = 2;
						} else if (date.after(date2)) {// 超时
							flag = 1;
						} else {// 准时
							flag = 0;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e);
		}

		return flag;
	}

	/** 订单物流状态-客户查看 */
	@Override
	public void getOrderStatus(String u_id, String titles, Map<String, Object> map) {
		// 根据订单号--查询配送--更新物流表物流状态
		/**
		 * 0：未派单 1：已派单 2：已抢单 3: 已到商家 4：取货 5: 货已送出 6：货已送达
		 */
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(titles);
		ApiT_shipping shipping = apiT_shippingMapper.findT_shippingByOrderId(titles);
		ApiTmember member = new ApiTmember();
		if (shipping == null) {
			shipping = new ApiT_shipping();
			shipping.setOrder_id(titles);
			shipping.setStatus(0);
			shipping.setCreate_time_str(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(dingDan.getAppdate()));
		} else {
			shipping.setCreate_time_str(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(dingDan.getAppdate()));
			if (6 == shipping.getStatus()) {
				shipping.setStatus(5);// 货已送达
			}
			if (!Util.isNull(shipping.getUser_id())) {
				member = apiTmemberMapper.findMemberByCuserid(shipping.getUser_id());
			}
		}
		InitUserOrderStatusPage initUserOrderStatusPage = new InitUserOrderStatusPage();
		initUserOrderStatusPage.setShipping(shipping);
		initUserOrderStatusPage.setMember(member);
		map.put("datas", initUserOrderStatusPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");

	}

	/** 充值有礼页面初始化 */
	@Override
	public void chargeWithGiftInit(Map<String, String> params, Map<String, Object> map) {
		String u_id = params.get("u_id");
		String product_ids = params.get("product_ids");
		String chargeMoney = params.get("chargeMoney");

		InitOrderPage orderPage = new InitOrderPage();
		// 根据u_id 返回用户信息，默认收货地址
		ApiTmember member = new ApiTmember();
		member = apiTmemberMapper.findMemberByCuserid(u_id);
		// t_address 收货地址
		ApiAddress address = new ApiAddress();
		address = apiAddressMapper.searchAddressByUid(u_id);
		// 如果没有默认地址---则返回地址中的第一个
		if (address == null) {
			List<ApiAddress> addressList = apiAddressMapper.searchAllAddressByUid(u_id);
			if (addressList != null && addressList.size() > 0) {
				address = addressList.get(0);
			}
		}
		// 解析购物单c_ids---不用解析，直接去数据库查询 in
		// orderPage = getShopListByCids(c_ids);

		// 根据product_ids 查询
		orderPage = getProductListByproductids(product_ids);
		orderPage.setSumPrice(Util.getBigDecimal(chargeMoney));

		orderPage.setMember(member);
		orderPage.setAddress(address);
		map.put("datas", orderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/**
	 * 先插入购物车-再调用生成订单的方法
	 * 
	 * @throws Exception
	 */
	@Transactional
	@Override
	public void chargeWithGiftConfirm(OrderConfirmPage orderConfirmPage, Map<String, Object> map) throws Exception {
		Integer autoReceiveOrder = Integer.parseInt(startOnLoadService.dictionaryMap().get("AUTORECEIVEORDER"));
		/**
		 * u_id:用户名----1：用户真实姓名，手机号 2：默认收货地址 c_ids:购物车ids---商品放到购物车的记录
		 * -----店铺名+商品 -----计算总的价格出来--需要再比对一次 收获地址：address:id 备注：remark
		 * 付款方式：payType 0:余额支付 1:支付宝 2:微信 3:货到付款 优惠券：------暂时先不写 配送费：sendfee
		 * 在线支付立减优惠活动---不写先--- 订单总金额 sumPrice
		 * 
		 * 需要校验：1-商品库存是否充足 2-后台计算金额与前台传过来的是否一致 多个商铺-一个商铺生成一个订单------
		 * 订单成功后，更新购物车状态，---已成单
		 */
		// 校验日期
		if (apiCarService.checkSendTime(orderConfirmPage, map)
				&& apiCarService.checkOrderAddress(orderConfirmPage, map)) {
			// 写插入购物车的方法
			String u_id = orderConfirmPage.getU_id();
			String product_idss = orderConfirmPage.getProduct_ids();
			String[] ids = product_idss.split(",");
			String c_ids = "";
			Map<Long, Integer> carMap = new HashMap<Long, Integer>();
			if (ids != null && ids.length > 0) {
				for (String productid : ids) {
					ApiCar car = new ApiCar();
					car.setU_id(u_id);
					car.setCount(1);
					Long product_id = Long.parseLong(productid);
					ApiT_products product = apiT_productsMapper.findT_productsById(product_id);
					car.setProduct_id(product_id);
					car.setGoods_id(product.getGoods_id());
					Date now = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
					car.setCreate_date(dateFormat.format(now));
					car.setStatus(0);
					car.setCity_id(product.getCity_id());
					car.setShop_id(product.getShop_id());
					apiCarMapper.addCar(car);
					c_ids = c_ids + car.getId() + ",";
					carMap.put(product_id, car.getId());
				}
				c_ids = c_ids.substring(0, c_ids.length() - 1);
			}
			orderConfirmPage.setC_ids(c_ids);
			if (apiCarService.checkProductsCharge(orderConfirmPage, map)) {
				// 保存订单信息
				// 返回：订单总额 账户余额 第三方账户还需支付
				Integer address_id = orderConfirmPage.getAddress_id();
				String remark = orderConfirmPage.getRemark();
				Integer payType = orderConfirmPage.getPayType();
				String sumPrice = orderConfirmPage.getSumPrice();
				BigDecimal sumPriceCheck =BigDecimal.ZERO;
				// 根据地址id获取用户的地址
				ApiAddress addressPage = apiAddressMapper.searchAddressByid(address_id);
				String address = addressPage.getCity() + addressPage.getAddress();// 收货地址
				String name = addressPage.getName();// 收货人姓名
				String mobile = addressPage.getPhone();// 收货人电话
				String longitude = addressPage.getLongitude();
				String latitude = addressPage.getLatitude();
				InitOrderPage orderPage = getShopListByCids(orderConfirmPage.getC_ids());
				List<CarShopPage> shopList = orderPage.getShopList();
				List<ApiDingDan> orderList = null;

				Map<Integer, String> sendTimeMap = orderConfirmPage.getSendTimeMap();

				if (shopList != null && shopList.size() > 0) {
					/** 更新购物车信息 */
					Map<String, Object> carparams = new HashMap<String, Object>();
					/** 更新订单明细 */
					List<ApiDingAss> dingAssList = new ArrayList<ApiDingAss>();

					List<Integer> cIdList = new ArrayList<Integer>();

					orderList = new ArrayList<ApiDingDan>();
					InitPaymentPage paymentPage = new InitPaymentPage();
					String orderIds = "";
					String orderIdFlag = "";
					for (CarShopPage shopPage : shopList) {
						ApiDingDan apiDingDan = new ApiDingDan();
						Integer shop_id = shopPage.getShop_id();
						apiDingDan.setU_id(u_id);
						apiDingDan.setShop_id(shop_id);
						apiDingDan.setSumGoodsPrice(BigDecimal.ZERO);
						apiDingDan.setSendFee(BigDecimal.ZERO);
						BigDecimal money = shopPage.getSumShopPrice().add(shopPage.getSendfee());// 商品金额+配送费
						apiDingDan.setMoney(Util.getBigDecimal(sumPrice));
						apiDingDan.setPayMoney(Util.getBigDecimal(sumPrice));
						sumPriceCheck = sumPriceCheck.add(apiDingDan.getMoney());

						String sendDate = sendTimeMap.get(shop_id);
						apiDingDan.setSendDate(sendDate);

						apiDingDan.setBz(remark);
						if (payType >= 0 && payType <= 3) {// 0:余额支付 1:支付宝 2:微信
															// 3:货到付款
							apiDingDan.setZf_type(payType + "");// 支付方式
						}
						List<CarOrderPage> carList = shopPage.getCarList();
						List<String> idList = new ArrayList<String>();
						Integer is_ziying = 0;
						if (carList != null && carList.size() > 0) {
							String car_ids = "";
							String product_ids = "";
							String tel = "";
							for (CarOrderPage carPage : carList) {
								tel = tel + carPage.getGoods_id() + ",";
								product_ids = product_ids + carPage.getProduct_id() + ",";
								car_ids = car_ids + carMap.get(carPage.getProduct_id()) + ",";
								is_ziying = carPage.getIs_ziying();
								carPage.setC_id(carMap.get(carPage.getProduct_id()));
								apiCarService.updateCar(carPage);
							}
							tel = tel.substring(0, tel.length() - 1);
							product_ids = product_ids.substring(0, product_ids.length() - 1);
							car_ids = car_ids.substring(0, car_ids.length() - 1);
							apiDingDan.setTel(tel);
							apiDingDan.setProduct_ids(product_ids);
							apiDingDan.setCar_ids(car_ids);

						}
						ApiT_city city = cityMapper.findT_cityById(carList.get(0).getCity_id());
						String titles = Utils.getDingDanNo(city.getU_name());
						apiDingDan.setTitles(titles);
						apiDingDan.setAddress(address);
						apiDingDan.setName(name);
						apiDingDan.setMobile(mobile);
						apiDingDan.setLatitude(latitude);
						apiDingDan.setLongitude(longitude);
						apiDingDan.setZi_status(0);// 0:已下单未支付 1:已支付 2:已退款
						apiDingDan.setEnable(1);// 1： 已下订单 2送餐员领取任务 3 用户未领取
												// 4用户已领取 5
												// 订单完成 6订单因故未完成 原因 9删除
						apiDingDan.setOrderType(2);// 0-购物订单 1-充值订单 2-充值有礼
						apiDingDan.setAppdate(new Date());
						/**
						 * 物流状态：根据是否自营 非自营：1-商家未确认 自营：数据库配置开关-是否自动接单 1-自动接单
						 * 0-待商家确认 1:商户未确认 2:商户确认接受订单 3:等待配送接单 4:配送确认接受订单
						 * 5:配送取货成功(配送中) 6:用户确认收货 7:退货
						 */
						Integer dd_status = 2;
						// 充值有礼自动接单
						apiDingDan.setDd_status(dd_status);// 1-商家未确认
						apiDingDan.setIs_send(1);// 默认一定配送
						orderList.add(apiDingDan);
						apiDingDan.setOrderNum(apiDingDanMapper.searchMaxOrderNumByShopId(shop_id)+"");
						apiDingDanMapper.saveDingDan(apiDingDan);// -
																	// -------------保存订单

						orderIds = orderIds + titles + ",";
						if ("".equals(orderIdFlag)) {
							orderIdFlag = apiDingDan.getTitles();
						}
						// 赋值id
						if (carList != null && carList.size() > 0) {
							for (CarOrderPage carPage : carList) {
								ApiDingAss dingAss = new ApiDingAss();
								dingAss.setDid(apiDingDan.getRid());
								dingAss.setRid(carPage.getGoods_id());
								dingAss.setProduct_id(carPage.getProduct_id());
								dingAss.setMoney(carPage.getPrice());
								dingAss.setNum(carPage.getCount());
								cIdList.add(carPage.getC_id());// --------购物单ids
								// 保存订单详细：
								apiDingAssMapper.saveDingAss(dingAss);
							}
						}

						/** 消息推送，每次新产生订单，给商家推送消息 */
						apiTOrderMessageService.sendShopNewOrderMessage(apiDingDan);

						// 生成订单后，商家已接单，添加配送任务---未付款的还没有配送任务
						apiT_shippingService.produceSendTask(apiDingDan);

					}
					orderIds = orderIds.substring(0, orderIds.length() - 1);

					ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
					paymentPage.setU_id(u_id);
					paymentPage.setCmoney(member.getCmoney());
					paymentPage.setSumPrice(sumPriceCheck);
					paymentPage.setOrderIds(orderIds);
					paymentPage.setOrderIdFlag(orderIdFlag);
					map.put("datas", paymentPage);
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "success");

				} else {
					map.put(Utils.RESULT, "-1111");
					map.put(Utils.MESSAGE, "购物记录不存在，请返回选择！");
				}
			}
		}
	}

	/** 积分商城订单页面初始化 */
	@Override
	public void initPointsOrder(Map<String, String> params, Map<String, Object> map) {
		String u_id = params.get("u_id");
		String act_ids = params.get("act_ids");

		InitOrderPage orderPage = new InitOrderPage();
		// 根据u_id 返回用户信息，默认收货地址
		ApiTmember member = new ApiTmember();
		member = apiTmemberMapper.findMemberByCuserid(u_id);
		// t_address 收货地址
		ApiAddress address = new ApiAddress();
		address = apiAddressMapper.searchAddressByUid(u_id);
		// 如果没有默认地址---则返回地址中的第一个
		if (address == null) {
			List<ApiAddress> addressList = apiAddressMapper.searchAllAddressByUid(u_id);
			if (addressList != null && addressList.size() > 0) {
				address = addressList.get(0);
			}
		}
		// 解析购物单c_ids---不用解析，直接去数据库查询 in
		orderPage = getProductListByactids(act_ids);
		orderPage.setMember(member);
		orderPage.setAddress(address);
		map.put("datas", orderPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");

	}

	/** 积分商城确认订单 */
	@Transactional
	@Override
	public void confirmPointsOrder(OrderConfirmPage orderConfirmPage, Map<String, Object> map) throws Exception {
		Integer autoReceiveOrder = Integer.parseInt(startOnLoadService.dictionaryMap().get("AUTORECEIVEORDER"));
		/**
		 * u_id:用户名----1：用户真实姓名，手机号 2：默认收货地址 c_ids:购物车ids---商品放到购物车的记录
		 * -----店铺名+商品 -----计算总的价格出来--需要再比对一次 收获地址：address:id 备注：remark
		 * 付款方式：payType 0:余额支付 1:支付宝 2:微信 3:货到付款 优惠券：------暂时先不写 配送费：sendfee
		 * 在线支付立减优惠活动---不写先--- 订单总金额 sumPrice
		 * 
		 * 需要校验：1-商品库存是否充足 2-后台计算金额与前台传过来的是否一致 多个商铺-一个商铺生成一个订单------
		 * 订单成功后，更新购物车状态，---已成单------这里直接生产订单，无需支付
		 */
		// 校验日期
		if (apiCarService.checkSendTime(orderConfirmPage, map) && apiCarService.checkOrderAddress(orderConfirmPage, map)
				&& apiCarService.checkOrderPoints(orderConfirmPage, map)) {
			// 写插入购物车的方法---price---存积分
			String u_id = orderConfirmPage.getU_id();
			String act_ids = orderConfirmPage.getAct_ids();
			String[] ids = act_ids.split(",");
			String c_ids = "";
			Map<Long, Integer> actCarMap = new HashMap<Long, Integer>();
			if (ids != null && ids.length > 0) {
				for (String actid : ids) {
					ApiCar car = new ApiCar();
					car.setU_id(u_id);
					car.setCount(1);
					Integer act_id = Integer.valueOf(actid);
					ApiT_goods_activity act = apiT_goods_activityMapper.findT_goods_activityById(act_id);
					car.setProduct_id(act.getProduct_id());
					car.setGoods_id(act.getGoods_id());
					Date now = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
					car.setCreate_date(dateFormat.format(now));
					car.setStatus(0);
					car.setCity_id(act.getCity_id());
					apiCarMapper.addCar(car);
					c_ids = c_ids + car.getId() + ",";
					actCarMap.put(act.getProduct_id(), car.getId());
				}
				c_ids = c_ids.substring(0, c_ids.length() - 1);
			}
			orderConfirmPage.setC_ids(c_ids);
			if (apiCarService.checkProductsCharge(orderConfirmPage, map)) {
				// 保存订单信息
				// 返回：订单总额 账户余额 第三方账户还需支付
				Integer address_id = orderConfirmPage.getAddress_id();
				String remark = orderConfirmPage.getRemark();
				Integer payType = orderConfirmPage.getPayType();
				String sumPrice = orderConfirmPage.getSumPrice();
				BigDecimal sumPriceCheck =BigDecimal.ZERO;
				// 根据地址id获取用户的地址
				ApiAddress addressPage = apiAddressMapper.searchAddressByid(address_id);
				String address = addressPage.getCity() + addressPage.getAddress();// 收货地址
				String name = addressPage.getName();// 收货人姓名
				String mobile = addressPage.getPhone();// 收货人电话
				String longitude = addressPage.getLongitude();
				String latitude = addressPage.getLatitude();
				InitOrderPage orderPage = getProductListByactids(act_ids);
				List<CarShopPage> shopList = orderPage.getShopList();
				List<ApiDingDan> orderList = null;

				Map<Integer, String> sendTimeMap = orderConfirmPage.getSendTimeMap();
				System.out.println("shopList:" + shopList);
				if (shopList != null && shopList.size() > 0) {
					orderList = new ArrayList<ApiDingDan>();
					InitPaymentPage paymentPage = new InitPaymentPage();
					String orderIds = "";
					String orderIdFlag = "";
					for (CarShopPage shopPage : shopList) {
						ApiDingDan apiDingDan = new ApiDingDan();
						Integer shop_id = shopPage.getShop_id();
						apiDingDan.setU_id(u_id);
						apiDingDan.setShop_id(shop_id);
						apiDingDan.setSumGoodsPrice(shopPage.getSumShopPrice());
						apiDingDan.setSendFee(BigDecimal.ZERO);
						BigDecimal money = shopPage.getSumShopPrice().add(shopPage.getSendfee());// 商品金额+配送费
						apiDingDan.setMoney(money);
						apiDingDan.setPayMoney(BigDecimal.ZERO);
						apiDingDan.setSumPoints(shopPage.getSumPoints());
						sumPriceCheck = sumPriceCheck.add(apiDingDan.getMoney());

						String sendDate = sendTimeMap.get(shop_id);
						apiDingDan.setSendDate(sendDate);

						apiDingDan.setBz(remark);
						apiDingDan.setZf_type("4");// 支付方式4-积分兑换
						List<CarOrderPage> carList = shopPage.getCarList();
						Integer is_ziying = 0;
						if (carList != null && carList.size() > 0) {
							String car_ids = "";
							String product_ids = "";
							String tel = "";
							for (CarOrderPage carPage : carList) {
								tel = tel + carPage.getGoods_id() + ",";
								product_ids = product_ids + carPage.getProduct_id() + ",";
								car_ids = car_ids + actCarMap.get(carPage.getProduct_id()) + ",";
								is_ziying = carPage.getIs_ziying();
								carPage.setC_id(actCarMap.get(carPage.getProduct_id()));
								apiCarService.updateCar(carPage);
							}
							tel = tel.substring(0, tel.length() - 1);
							product_ids = product_ids.substring(0, product_ids.length() - 1);
							car_ids = car_ids.substring(0, car_ids.length() - 1);
							apiDingDan.setTel(tel);
							apiDingDan.setProduct_ids(product_ids);
							apiDingDan.setCar_ids(car_ids);

						}
						ApiT_city city = cityMapper.findT_cityById(carList.get(0).getCity_id());
						String titles = Utils.getDingDanNo(city.getU_name());
						apiDingDan.setTitles(titles);
						apiDingDan.setAddress(address);
						apiDingDan.setName(name);
						apiDingDan.setMobile(mobile);
						apiDingDan.setLatitude(latitude);
						apiDingDan.setLongitude(longitude);
						apiDingDan.setZi_status(1);// 0:已下单未支付 1:已支付 2:已退款
						apiDingDan.setEnable(1);// 1： 已下订单 2送餐员领取任务 3 用户未领取
												// 4用户已领取 5
												// 订单完成 6订单因故未完成 原因 9删除
						apiDingDan.setOrderType(3);// 0-购物订单 1-充值订单 2-充值有礼
													// 3-积分兑换
						apiDingDan.setAppdate(new Date());
						apiDingDan.setPaytime(new Date());
						// 积分兑换--自动接单
						apiDingDan.setDd_status(2);// 1-商家未确认
						apiDingDan.setIs_send(1);// 默认一定配送
						orderList.add(apiDingDan);
						apiDingDan.setOrderNum(apiDingDanMapper.searchMaxOrderNumByShopId(shop_id)+"");
						apiDingDanMapper.saveDingDan(apiDingDan);// -
																	// -------------保存订单

						orderIds = orderIds + titles + ",";
						if ("".equals(orderIdFlag)) {
							orderIdFlag = apiDingDan.getTitles();
						}
						// 赋值id
						if (carList != null && carList.size() > 0) {
							for (CarOrderPage carPage : carList) {
								ApiDingAss dingAss = new ApiDingAss();
								dingAss.setDid(apiDingDan.getRid());
								dingAss.setRid(carPage.getGoods_id());
								dingAss.setProduct_id(carPage.getProduct_id());
								dingAss.setMoney(carPage.getPrice());
								dingAss.setNum(carPage.getCount());
								dingAss.setPoints(carPage.getPoints());
								// 保存订单详细：
								apiDingAssMapper.saveDingAss(dingAss);
							}
						}

						/** 消息推送，每次新产生订单，给商家推送消息 */
						apiTOrderMessageService.sendShopNewOrderMessage(apiDingDan);

						// 生成订单后，商家已接单，添加配送任务---未付款的还没有配送任务
						apiT_shippingService.produceSendTask(apiDingDan);

					}
					orderIds = orderIds.substring(0, orderIds.length() - 1);

					ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
					Integer oldcJf = member.getcJf();// 原积分
					// 减除积分
					member.setcJf(member.getcJf() - orderPage.getSumPoints());
					apiTmemberMapper.updateApiTmember(member);
					// 进入积分明细
					ApiT_member_point apiT_member_point = new ApiT_member_point();
					apiT_member_point.setAddtime(Util.CurrentTime());
					apiT_member_point.setChange_point(orderPage.getSumPoints());
					apiT_member_point.setPoint(oldcJf);
					apiT_member_point.setConsume_point(orderPage.getSumPoints());
					apiT_member_point.setRemark("购买积分商品");
					apiT_member_point.setMember_id(member.getCid().toString());
					apiT_member_point.setType(1);// 支出
					apiT_member_pointMapper.insertT_member_point(apiT_member_point);

					paymentPage.setU_id(u_id);
					paymentPage.setCmoney(member.getCmoney());
					paymentPage.setSumPrice(sumPriceCheck);
					paymentPage.setOrderIds(orderIds);
					paymentPage.setOrderIdFlag(orderIdFlag);
					map.put("datas", paymentPage);
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "success");

				} else {
					map.put(Utils.RESULT, "-1111");
					map.put(Utils.MESSAGE, "购物记录不存在，请返回选择！");
				}
			}
		}
	}

	@Override
	public List<Map<String, Object>> backShopOrder(Cond cond) {
		List<Map<String, Object>> order = new ArrayList<Map<String, Object>>();
		order = apiDingDanMapper.backShopOrder(cond);
		for (Map<String, Object> map : order) {
			Object enable = map.get("enable");// 订单
			Object ddstatus = map.get("dd_status");// 订单
			Object zistatus = map.get("zi_status");// 订单
			Object zftype = map.get("zf_type");// 订单
			Object spstatus = map.get("spstatus");// 配送
			Integer ienable = -1;
			Integer iddstatus = -1;
			Integer izistatus = -1;
			Integer ispstatus = -1;
			Integer izftype = -1;
			String str = "";
			if (enable != null && !"".equals(enable) && ddstatus != null && !"".equals(ddstatus) && zistatus != null
					&& !"".equals(zistatus)) {
				ienable = Integer.parseInt(enable + "");
				iddstatus = Integer.parseInt(ddstatus + "");
				izistatus = Integer.parseInt(zistatus + "");
				if (ienable == 1 && iddstatus == 1 && izistatus == 1) {
					str = "待处理";
				} else if (ienable == 1 && iddstatus == 1 && izistatus == 0) {
					if (zftype != null && !"".equals(zftype)) {
						izftype = Integer.parseInt(zftype + "");
						if (izftype == 3) {
							str = "待处理";
						}
					}
				}
			}
			if (spstatus != null && !"".equals(spstatus)) {
				ispstatus = Integer.parseInt(spstatus + "");
				if (ispstatus < 4) {
					str = "正在处理";
				}
			}
			if (spstatus != null && !"".equals(spstatus)) {
				ispstatus = Integer.parseInt(spstatus + "");
				if (ispstatus > 3) {
					str = "配送中";
				}
			}
			if (enable != null && !"".equals(enable)) {
				ienable = Integer.parseInt(enable + "");
				if (ienable == 5) {
					str = "已完成";
				}
			}
			if (izftype == 0) {
				map.put("zf_type", "余额支付");
			} else if (izftype == 1) {
				map.put("zf_type", "支付宝");
			} else if (izftype == 2) {
				map.put("zf_type", "微信");
			} else if (izftype == 3) {
				map.put("zf_type", "货到付款");
			}
			map.put("str", str);
		}
		return order;
	}

	@Override
	public List<Map<String, Object>> searchOrder(Map<String, Object> conditions, PageInfo pageInfo) {
		return apiDingDanMapper.searchOrderListPage(conditions, pageInfo);
	}

	@Override
	public List<Map<String, Object>> getOrderListPage(Map<String, Object> conditions, PageInfo pageInfo) {
		return apiDingDanMapper.getOrderListPage(conditions, pageInfo);
	}

	/** 取消的订单---如果付款--退款到余额 */
	@Transactional
	@Override
	public void refundPaymoneyByCancelOrder(ApiDingDan dingDan) {
		if (dingDan != null) {
			Integer zi_status = dingDan.getZi_status();
			BigDecimal payMoney = dingDan.getPayMoney();
			Integer enable = dingDan.getEnable();
			String u_id = dingDan.getU_id();
			if ((enable == 4 || enable == 2) && zi_status == 1) {
				ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
				BigDecimal cmoney = member.getCmoney();
				if (cmoney == null) {
					cmoney =BigDecimal.ZERO;
				}
				cmoney = cmoney.add(payMoney);
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("cUserId", u_id);
				params.put("cMoney", cmoney);
				apiTmemberMapper.modifyApiTmemberByCuserid(params);
				dingDan.setZi_status(2);// 已退款
			}
		}
	}

	@Override
	public boolean checkReturnGoods(String orderId, Map<String, Object> map) {
		// 根据订单号，查询订单信息
		boolean flag = true;
		ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(orderId);
		if (dingDan != null) {
			Integer enable = dingDan.getEnable();
			Date takeGoodsTime = dingDan.getTakeGoodsTime();
			if (5 == enable) {// 已完成，判断时间
				Integer shop_id = dingDan.getShop_id();
				ApiShop shop = apiShopsMapper.findT_shopsById(shop_id);
				Integer city_id = shop.getC_city_id();
				ApiT_city city = cityMapper.findT_cityById(city_id);
				Integer day = city.getReturn_goods_time();
				Date now_date = new Date();
				long duringTime = now_date.getTime() - takeGoodsTime.getTime();
				long dayTime = day * 24 * 60 * 60 * 1000;// 数据库配置的时间
				if (duringTime >= dayTime) {// 收货后持续的时间大于配置的时间--不允许退货
					flag = false;
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, city.getName() + "确认收货超出" + day + "天，不允许退货！");
				}

			}
		}
		return flag;
	}

	public Integer getShopDingDanSize(HashMap map) {
		return apiDingDanMapper.getShopDingDanSize(map);
	}

	public List<AccountPage> searchMyBalanceListPage(HashMap map, PageInfo page) {
		return apiDingDanMapper.searchMyBalanceListPage(map, page);
	}

	public ApiDingDan searchDingDanById(Integer c_id) {
		return apiDingDanMapper.searchDingDanById(c_id);
	}

	public void updateApiDingDan(ApiDingDan apiDingDan) {
		apiDingDanMapper.updateDingDan(apiDingDan);
	}

	@Override
	public String getProductIdsByOrderNum(String orderNum,List<String> productIds) {
		// TODO Auto-generated method stub
		return apiT_orderMapper.getProductIdsByOrderNum(orderNum,productIds);
	}

	@Override
	public void updPlStatusByOrderNum(String orderNum) {
		 apiT_orderMapper.updPlStatusByOrderNum(orderNum);
		
	}

	@Override
	public Map<String, Object> getOrderInfoByOrderNum(String orderNum) {
		// TODO Auto-generated method stub
		return apiT_orderMapper.getOrderInfoByOrderNum(orderNum);
	}

		

}
